Why not just use await with timeout?
boolean await(long timeout, TimeUnit unit);
If the specified waiting time elapses then the value false is returned, otherwise true is returned on await completion.
Abort countDownLatch.await() after time out
If you want to stop execution of other threads, if any thread fails - you'll need some additional communication layer.
For example:
AtomicBoolean kill = new AtomicBoolean(false);
CountDownLatch latch = new CountDownLatch(SOME_NUM);
class Task extends Runnable {
public void run() {
try {
....
if (kill.get())
throw new Exception();
....
} catch (Throwable throwable) {
kill.set(true);
} finally {
countDownLatch.countDown();
}
}
}
If you just want to release count down on Throwable, regardless of other processes, you can do countDown in loop on Exception
class Task extends Runnable {
public void run() {
try {
....
} catch (Throwable throwable) {
while(countDownLatch.getCount() != 0)
countDownLatch.countDown();
} finally {
countDownLatch.countDown();
}
}
}
You can combine 2 countDown tasks
CountDownLatch A = new CountDownLatch(1);
CountDownLatch B = new CountDownLatch(1);
class CountDownTracker extend Runnable {
public void run() {
B.await();
A.countDown();
}
}
class Task extends Runnable {
public void run() {
try {
....
} catch (Throwable throwable) {
A.countDown();
} finally {
B.countDown();
}
}
}
in this case A will finish after completion, or any Task failure.
And so on...