java - Why does notifyAll() raise IllegalMonitorStateException when synchronized on Integer? -


why test program result in java.lang.illegalmonitorstateexception?

public class test {     static integer foo = new integer(1);     public static void main(string[] args) {         synchronized(foo) {             foo++;             foo.notifyall();         }         system.err.println("success");     } } 

result:

exception in thread "main" java.lang.illegalmonitorstateexception         @ java.lang.object.notifyall(native method)         @ test.main(test.java:6) 

you have noted correctly notifyall must called synchronized block.

however, in case, because of auto-boxing, object synchronized on not same instance invoked notifyall on. in fact, new, incremented foo instance still confined stack, , no other threads possibly blocked on wait call.

you implement own, mutable counter on synchronization performed. depending on application, might find atomicinteger meets needs.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -