0

I have this simple schema:

int parallelism = 4; //4 tasks
ExecutorService executor = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(parallelism);

for(int i=0;i<parallelism;i++){
   executor.execute(new MyTask());
}

latch.await();
System.out.println("done");

Where Task just calls

public void run(){
      System.out.println("working");
      latch.countDown();
}

Even though execution gives me:

working
working
working
working
done

the overall program keep executing! How come?

Phate
  • 6,066
  • 15
  • 73
  • 138
  • 1
    It is working as expected.. The main thread is waiting until all other threads have called `countDown()`. What did you expect? – TheLostMind May 26 '15 at 12:45

1 Answers1

3

You need to shut down your Executor.

    ExecutorService executor = Executors.newCachedThreadPool();
    // ...
    executor.shutdown();
    while ( executor.awaitTermination(1, TimeUnit.SECONDS)) {
        System.out.println("This is taking too long.");
    }

Even though all of your runnables have completed the Executor keeps the threads in a pool. These are what is holding up your exit. The main thread will not exit until all non-daemon threads have completed.

Also see Turning an ExecutorService to daemon in Java for another alternative - making the Executor use daemon threads.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213