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?
Have you considered using
wait/notify(the equivalent ofMonitor.WaitandMonitor.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
CountDownLatchmay well do what you want.EDIT: I’ve only just noticed that
CountDownLatchis basically “single use” – you can’t reset the count later, as far as I can see. You may wantSemaphoreinstead. UsetryAcquirelike this to wait with a timeout:Note that this is unlike
ManualResetEventin that each successful call totryAcquirewill reduce the number of permits – so eventually they’ll run out again. You can’t make it permanently “set” like you could withManualResetEvent. (That would work withCountdownLatch, but then you couldn’t “reset” it 🙂