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 unle
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 :)