javamultithreadingthreadgroup

Join a group of threads with overall timeout


Is there a way to join a group of threads simultaneously with an overall timeout?

Suppose we have Collection<Thread> threads; and int timeout;. If I didn't care about the timeout, I would do

for (Thread t : threads)
    t.join();

but I want to wait until either all threads are done, or a certain amount of time passes, whichever comes first. I was searching for a (hypothetical) ThreadGroup.join(int) which would do this.


Note that what I'm asking for is different from doing

for (Thread t : threads)
    t.join(timeout);

Rather, I'm looking for something less verbose (and perhaps more reliable) than

int timeout = 10000;
for (Thread t : threads) {
    if (timeout <= 0) break;

    long start = System.currentTimeMillis();
    t.join(timeout);
    long end = System.currentTimeMillis();

    // substract time elapsed from next timeout:
    timeout -= (int) (end - start);
}

Solution

  • First create a single CountDownLatch having a count for every thread in the group.

    A controlling thread can await(timeout, TimeUnit) on the latch.

    https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html#await-long-java.util.concurrent.TimeUnit-

    Start the threads that are in the group.

    Each of the threads in the group should decrement the latch when it completes.

    The controlling thread will wait until everything in the group has completed or the timeout happens, and because await returns a boolean, the controlling thread can tell whether the latch was decremented naturally or whether a timeout occurred.