Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for a ThreadPoolExecutor to finish

My Question: How to execute a bunch of threaded objects on a ThreadPoolExecutor and wait for them all to finish before moving on?

I'm new to ThreadPoolExecutor. So this code is a test to learn how it works. Right now I don't even fill the BlockingQueue with the objects because I don't understand how to start the queue without calling execute() with another RunnableObject. Anyway, right now I just call awaitTermination() but I think I'm still missing something. Any tips would be great! Thanks.

public void testThreadPoolExecutor() throws InterruptedException {   int limit = 20;   BlockingQueue q = new ArrayBlockingQueue(limit);   ThreadPoolExecutor ex = new ThreadPoolExecutor(limit, limit, 20, TimeUnit.SECONDS, q);   for (int i = 0; i < limit; i++) {     ex.execute(new RunnableObject(i + 1));   }   ex.awaitTermination(2, TimeUnit.SECONDS);   System.out.println("finished"); } 

The RunnableObject class:

package playground;  public class RunnableObject implements Runnable {    private final int id;    public RunnableObject(int id) {     this.id = id;   }    @Override   public void run() {     System.out.println("ID: " + id + " started");     try {       Thread.sleep(2354);     } catch (InterruptedException ignore) {     }     System.out.println("ID: " + id + " ended");   } } 
like image 224
kentcdodds Avatar asked Jun 07 '12 14:06

kentcdodds


People also ask

Do we need to close ExecutorService?

ExecutorService must be shutdown explicitly to reclaim the resources (CPU & Memory) occupied by threads which have already finished their job but still exist.

How do you prevent ThreadPoolExecutor?

The ThreadPoolExecutor in Python provides a thread pool that lets you run tasks concurrently. You can add tasks to the pool by calling submit() with your function name, which will return a Future object. You can call the cancel() function on the Future object to cancel the task before it has started running.


1 Answers

You should loop on awaitTermination

ExecutorService threads; // ... // Tell threads to finish off. threads.shutdown(); // Wait for everything to finish. while (!threads.awaitTermination(10, TimeUnit.SECONDS)) {   log.info("Awaiting completion of threads."); } 
like image 82
OldCurmudgeon Avatar answered Oct 21 '22 00:10

OldCurmudgeon