The problem i face is i have a thread A and n works need to be done. Thread A must wait until this n works are completely done. My idea is using a CountDownLatch
with n count and use Producer/Consumer pattern to control the Worker.
I use an AtomicInteger
to serve as the counter: The Producer checks if the counter value is greater than 0 then put a signal to the BlockingQueue
, if counter value is less than or equal to 0, Producer put a stopSignal to the queue. The Consumer takes from the queue, checks whether the signal is not equals to stopSignal then use a ExecutorService
to schedule the Worker
.
The Worker call getAndDecrement
and check if counter's value is greater than 0, if yes then do the work,
if the work is done then it calls CountDownLatch#countdown else increase the counter with incrementAndGet
The problem is when a work isn't done, the Worker must increase the counter but this is after a getAndDecrement
so the Producer might see the value of counter to be 0 and put the stop signal even the total of work is less than n!