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
In theory, the ManualResetEvent class as given above is correct on Java 5 (but not earlier). Given the long history of incorrect (or inadequate) implementations of volatile, it seems wiser to me to add an additional synchronized block in reset() in order to generate a guaranteed write barrier, and ensure complete atomicity. The danger is that a read of "open" may pass a write of "open" on multi-processor Intel cpus. The advantage of the change given below: it may not be optimally efficient, but it does have the great advantage of being guaranteed to be not wrong, at very little additional cost.
class ManualResetEvent {
private final Object monitor = new Object();
private volatile boolean open = false;
public ManualResetEvent(boolean open) {
this.open = open; }
public void waitOne() throws InterruptedException {
synchronized (monitor) {
while (open==false) {
monitor.wait();
}
}
}
public void set() {//open start
synchronized (monitor) {
open = true;
monitor.notifyAll();
}
}
public void reset() {//close stop
synchronized(monitor) {
open = false;
}
}
}
Thanks to the original poster.