0

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!

robinmag
  • 17,520
  • 19
  • 54
  • 55

1 Answers1

1

Sounds like you are working on a typical Producer/Consumer problem with some added complexity (a new condition of waiting for exactly n work done). So as you have defined, you have Producers and Consumers. One makes work, the second consumes it.

Incrementing after the work has been created. Decrementing after the work has be consumed. This approach would have your workers trying to fetch from the queue only when there is work available.

Now to address your problem, the new condition you of waiting for n works to be completed. If you are waiting for a certain amount of jobs to finish and you are clearly aware of these jobs you could use the CyclicBarrier object to stop the flow until all the jobs have reached the barrier.

There are usually more ways two coordinate workers in a concurrent situation. Producer/Consumer might not be the solution to this problem, and neither might a Barrier. I would recommend looking in the java.util.concurrent package as it might shed more light on this subject.

Kevin Jalbert
  • 3,115
  • 3
  • 26
  • 39