0

What i need is a tool/class that acts like CoundDownLatch but can be counted up and down. Whenever a task is executed it will counted up, when a task is done it is counted down. There can be multiple tasks running parallel, and one thread should wait until no task is executing/ the counter is at 0.

I looked into the Phaser class, but i don't know if it provides what i am looking for, maybe it can be used to solve this puzzle?

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Chriss
  • 5,157
  • 7
  • 41
  • 75
  • 2
    This question appears to be off-topic, because you're requesting a third-party tool. You could store your threads in an array, and join on them to ensure they all complete before you exit. You might use [Future](http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html) to get the results, or you might do something else entirely. What design are you using, and where are you stuck? – Elliott Frisch Feb 28 '14 at 15:23

2 Answers2

1

You can use java.util.concurrent.locks.Condition together with ReentrantLock and AtomicInteger.

Pseudo code for task executor:

// start executing task
taskCounter.incrementAndGet();
// execute task
...
// stop executing task
if (taskCounter.decrementAndGet() == 0) {
    condition.signal();
}

Pseudo code for waiter thread:

condition.await();
hoaz
  • 9,883
  • 4
  • 42
  • 53
0

You should use an ExecutorService as discussed in How to wait for all threads to finish, using ExecutorService?.

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