0

I'm using CountDownLatches to wait for a specific even but I need to be able to abort its await() method and throw an exception right away.

It's not nearly a challenge but I'm wondering if Java has something out of the box to do that for me because it sounds like a reasonable option to have.

Example:

SpecialCountDownLatch latch = new SpecialCountDownLatch();

Thread-1:

latch.await();

Thread-2:

latch.interrupt(); // Forces latch.await() at Thread-1 to throw an exception
Muhammad Gelbana
  • 3,890
  • 3
  • 43
  • 81
  • According to the [`CountdownLatch.await()`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html#await--) Javadoc, this already works. – user207421 Sep 11 '20 at 09:41
  • 1
    The code for Thread-2 is presumably `thread1.interrupt();`, and there are several objects with blocking operations that could be used. `CountDownLatch` or `Semaphore` for example, depending on what you're doing. – Kayaman Sep 11 '20 at 09:50
  • I understand I can use `Thread.interrupt()` but I was wondering if it was possible to call something similar to `latch.interrupt()` because I won't have a reference to the thread that is blocked at `latch.await()` to interrupt it. It just came to me that the thread that called `latch.await()` is "Parked" or "Waiting" so I thinkg there is no way to interrupt the latch withoung actually calling `Thread.interrupt` for the "parked/waiting" thread! I suppose what I'm asking for is not possible. – Muhammad Gelbana Sep 12 '20 at 12:00

0 Answers0