'Join multiple threads with timeout
I need to join multiple threads with a timeout. Something like Thread.join(long millis)
but for multiple threads.
I found some posts about joining multiple threads, but not regarding joining with timeout.
The code I'm changing is:
for (Thread thread : threads) {
thread.join(units.toMillis(timeout));
}
But this obviously waits for each thread separately having the effect of waiting up to threads.length * timeout
. I want to wait up to timeout
for all threads altogether.
What would be the right way to do this?
Solution 1:[1]
Sounds like you're trying to implement a barrier with a timeout. Have you tried this: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CyclicBarrier.html
Solution 2:[2]
you can track elapsed time and join on timeout - elapsed, if it's negative, you don't need to wait at all, it's time-outed already
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | George |
Solution 2 | Pavel Niedoba |