Orca Orca - 6 months ago 83
Java Question

Java Equivalent of .NET's ManualResetEvent and WaitHandle

I would like to know if Java provides an equivalent of .NET's classes of ManualResetEvent and WaitHandle, as I would like to write code that blocks for a given timeout unless an event is triggered.

The .NET classes of WaitHandle and ManualResetEvent provide a nice, hassle-free interface for that which is also thread-safe as far as I know, so what does Java has to offer?

Answer

Have you considered using wait/notify (the equivalent of Monitor.Wait and Monitor.Pulse) instead?

You'll want a little bit of checking to see whether you actually need to wait (to avoid race conditions) but it should work.

Otherwise, something like CountDownLatch may well do what you want.

EDIT: I've only just noticed that CountDownLatch is basically "single use" - you can't reset the count later, as far as I can see. You may want Semaphore instead. Use tryAcquire like this to wait with a timeout:

if (semaphore.tryAquire(5, TimeUnit.SECONDS)) {
   ...
   // Permit was granted before timeout
} else {
   // We timed out while waiting
}

Note that this is unlike ManualResetEvent in that each successful call to tryAcquire will reduce the number of permits - so eventually they'll run out again. You can't make it permanently "set" like you could with ManualResetEvent. (That would work with CountdownLatch, but then you couldn't "reset" it :)