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
Post a Comment