Multi-threading: wait for tasks to complete
Hi all.
I was toying around with some multithreading code today. I ran into a
stick problem: how to wait for an unknown number of tasks to complete.
There seem to be a lot of Java classes that wait for a specific number
of threads or tasks: Semaphore and CountDownLatch, for example. But
there don't seem to be any that allow their value to be changed on the
fly to account for new tasks being created.
Maybe I missed an existing class?
Anyway, the solution I came up with was to roll my own latch, the
UpDownLatch. So named because it can count both up (for new tasks being
spawned) and down (for when the task completes).
Here's the code. Comments welcome. Obviously, it's currently a nested
class; that should be changed for general use.
private static class UpDownLatch
{
private int count;
public synchronized void countUp() {
count++;
}
public synchronized void countDown() {
count--;
if( count == 0 ) {
notifyAll();
}
}
public synchronized void await() throws InterruptedException {
while( count != 0 ) {
wait();
}
}
}