CountdownLatch countDown method behavior after completion of task

749 views Asked by At

Suppose i have a countdown latch of size 3 i.e. 3 threads are spawned off from parent thread.

CountDownLatch latch = new CountDownLatch(3);

latch.await().

Now there will be three threads which will be calling countDown after their respective task completion.

// do something
 latch.countDown();

My question is that the moment task gets completed whats the behavior of thread that was executing that task.

Does that thread gets terminated right at that moment, or waits for sometime by going into idle state. ?

I could find it anywhere on java doc of countdown latch.

2

There are 2 answers

1
Brett Walker On

It depends upon the code in the child threads. If there is more computation to do after the CountDownLatch it will then continue with the computation. If not, the the thread will termninate.

0
Mister Smith On

You are focusing too much on the typical example of having N subordinate threads signal to a master thread.

This CountDownLatch thing is just a class that allows code to block until some external agents count down the latch to 0. Period.

These agents can be N different threads as in your example, or it can be a single thread counting down multiple times. Therefore you should stop viewing those agents as threads. The latch doesn't know them and doesn't care if instead of completing they go have a beer at the pub after counting down. It is not a Thread Manager and it doesn't monitor the lifecycle of any thread.