multithreading - How does CountDownLatch works in Java? -
this question has answer here:
i studying synchronization in java. not able understand exact mechanism of countdownlatch.
does countdownlatch 'counts down latch' (waits completion of number of threads) per number of threads given @ declaration?
here code tried understand:
public class latchexample implements runnable { private countdownlatch latch; private int id; public latchexample(int id, countdownlatch latch){ this.id=id; this.latch = latch; } public static void main(string[] args) { countdownlatch latch = new countdownlatch(5); executorservice executor = executors.newfixedthreadpool(3); (int = 0; < 7; i++) { executor.submit(new latchexample(i,latch)); } try { latch.await(); system.out.println("all process completed"); } catch (interruptedexception e) { e.printstacktrace(); } system.out.println(); } @override public void run() { system.out.println("starting: "+id); try { thread.sleep(1000); } catch (interruptedexception e) { e.printstacktrace(); } latch.countdown(); } }
in example above:
7 threads spawned executorservice (from thread pool). understanding latch should wait completion of 6 threads (from 0 5), defined by:
countdownlatch latch = new countdownlatch(5);
but output not constant every time. waits 6 threads complete , waits 7 e.g.:
starting: 1 starting: 0 starting: 2 starting: 3 starting: 5 starting: 4 starting: 6 process completed
here output @ alternate times:
starting: 0 starting: 2 starting: 1 starting: 4 starting: 5 starting: 3 process completed starting: 6
edit : countdownlatch should ideally countdown until 5 tasks passed latch. here showing either 6 or 7.
what fix code, if want display 5 tasks before 'all process completed' ?
your latch need 5 countdown()
calls reach 0 , let await
return. however, way task executor written, more tasks start running needed release latch. helpful approach seeing code working through run step step, this:
- tasks 0-2 start running on 3 threadpool threads;
- you see
starting: n
printed 3 times,n
ranges between 0 , 2, in arbitrary order; - a second passes;
- the 3 tasks complete simultaneously, bringing latch's count down 2;
- tasks 3-5 start running;
- you see
starting: n
printed 3 times,n
ranging between 3 , 5, in arbitrary order; - another second passes;
- tasks 3-5 complete simultaneously, releasing latch. both main thread can continue , task 6 can start;
all processes completed
prints @ same timestarting: 6
, in arbitrary order.
now, not quite clear expected code do, hope above way of reasoning bring state behavior aligns expectation.
Comments
Post a Comment