Yesterday I noticed something very strange. It seems that two threads simultaneously enter two synchronized blocks on the same object.
The class ( MyClass ) containing the corresponding code looks something like this:
private static int[] myLock = new int[0]; protected static int methodA(final long handle, final byte[] sort) { synchronized (myLock) { return xsMethodA(handle, sort); } } protected static int methodB(final long handle) { synchronized (myLock) { return xsMethodB(handle); } }
I dumped the stream of my application working on the class, and was very surprised to see this:
"http-8080-136" daemon prio=10 tid=0x00000000447df000 nid=0x70ed waiting for monitor entry [0x00007fd862aea000] java.lang.Thread.State: BLOCKED (on object monitor) at com.MyClass.methodA(MyClass.java:750) - locked <0x00007fd8a6b8c790> (a [I) at com.SomeOtherClass.otherMethod(SomeOtherClass.java:226) ... "http-8080-111" daemon prio=10 tid=0x00007fd87d1a0000 nid=0x70c8 waiting for monitor entry [0x00007fd86e15f000] java.lang.Thread.State: BLOCKED (on object monitor) at com.MyClass.methodB(MyClass.java:991) - locked <0x00007fd8a6b8c790> (a [I) at com.SomeOtherClass.yetAnotherMethod(SomeOtherClass.java:3231) ...
(I changed the names of the classes and methods for simplicity, so do not confuse the stupid names.)
It seems that the streams http-8080-136 and http-8080-111 both acquired a lock on myLock . This is the same object as the object address: 0x00007fd8a6b8c790 . The Java Runtime specification speaks of the synchronized :
The synchronized statement obtains a mutual exclusion lock (§17.1) on behalf of the executing thread, executes the block, and then releases the lock. As long as the executing thread holds the lock, no other thread can get the lock . [ Java Language Specification, 14.19 ]
How is this possible?
There are another 44 threads in the thread date for blocking. It looks like this if the thread is expecting:
"http-8080-146" daemon prio=10 tid=0x00007fd786dab000 nid=0x184b waiting for monitor entry [0x00007fd8393b6000] java.lang.Thread.State: BLOCKED (on object monitor) at com.MyClass.methodC(MyClass.java:750) - waiting to lock <0x00007fd8a6b8c790> (a [I) at com.SomeOtherClass.yetAnoterMethod2(SomeOtherClass.java:226)
java multithreading concurrency synchronized
Eduard wirch
source share