I understand that the each Java object can be used as a Monitor. A thread can acquire the lock if the entry count associated with the object is zero. And if the same thread acquires the lock, the entry count is incremented thru the "monitorenter" opcode and is decremented when the same thread releases the code during "monitorexit". Where is this entry count stored? How is it linked to a Java object? Does it get allocated when the object is created?
Asked
Active
Viewed 281 times
0
-
https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.monitorenter is one of the references I was reading. – UnderWood Apr 01 '17 at 02:57
2 Answers
2
Each JVM may have different implementation of intrinsic locks. As to HotSpot JVM, it does not count lock entries at all, but rather reserves slots in the stack frames of methods with monitorenter
/monitorexit
bytecodes.
HotSpot JVM has two mechanisms for Java monitors:
- Biased Lock. The object is 'biased' toward the given thread by putting the thread ID in the object header. Then locking and unlocking in the given thread is almost a no-op: JVM just needs to verify that Biased Lock marker is still in the object header.
- Regular recursive lock. If a method has
synchronized
blocks (i.e.monitorenter
/monitorexit
) bytecodes, a place is reserved on the stack to record the lock info: an object and its displaced header (i.e. the header value before locking). If an object is locked recursively, the displaced header contains zero, so the VM knows that it should not update an object header onmonitorexit
.
More details in HotSpot sources.

apangin
- 92,924
- 10
- 193
- 247
0
This count is used internally in JVM and cannot be visible from your code. You can however count it for yourself, but be aware, that lock is released (counter in JVM decreased until 0) even, if Exception occurs in "synchronized" code.

Marvin
- 598
- 5
- 14