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?
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:
synchronized
blocks (ie monitorenter
/ monitorexit
) bytecodes, a place is reserved on the stack to record the lock info: an object and its displaced header (ie 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 on monitorexit
. More details in HotSpot sources .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.