Why does this test program result in a java.lang.IllegalMonitorStateException?
public class test {
static Integer foo = new Integer(1);
Incrementing the Integer makes the old foo disappear and be replaced with a brand new object foo which is not synchronized with the previous foo variable.
Here is an implementation of AtomicInteger that erickson suggested above. In this example foo.notifyAll(); does not produce a java.lang.IllegalMonitorStateException beause the AtomicInteger Object is not refreshed when foo.incrementAndGet(); is run.
import java.util.concurrent.atomic.AtomicInteger;
public class SynchronizeOnAPrimitive {
static AtomicInteger foo = new AtomicInteger(1);
public static void main(String[] args) {
synchronized (foo) {
foo.incrementAndGet();
foo.notifyAll();
}
System.out.println("foo is: " + foo);
}
}
Output:
foo is: 2