user3663882 user3663882 - 1 year ago 90
Java Question

Properly shut down ThreadPoolExecutors

I'm new to java concurrency an would like to ask the following basic question. I'm creating a ThreadPoolExecutor for imporving performance as follows:

int n = Runtime.getRuntime().availableProcessors()
ExecutorService executor = Executors.newFixedThreadPool(n);
for( int i = 0; i < n; i++)
executor.execute(new Work());

After all thread in the thread pool have finished their tasks I need to shutdown the pool properly. I would tried this:


But I'm not sure about that because I think we waste a lot of processors resources to queriyng the executor for termination.

What is the right solution for that?

UPD: Runnable task:

public class Work implements Runnable{

private String sql;

public Work() {
//init sql
public void run() {
JdbcTemplate template = new JdbcTemplate(dataSource);
List<Integer> ints = template.queryForList(sql, Integer.class);
//Storing the list into a global cache


Answer Source

There seems to be something mystical around shutting down an ExecutorService.

From the documentation of shutdown():

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

So all you have to do is to invoke shutdown() after you have submitted all your tasks, the exact time doesn’t matter. They don’t have to be completed at that time. The ThreadPoolExecutor will finish all tasks and then clean up all resources.

And it will do so regardless of whether you wait for it or not. So you don’t need to wait, just invoke shutdown() when you are confident that you will not submit new tasks, the rest will happen as soon as possible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download