简体   繁体   中英

Where is the entry count for an object stored in Java

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:

  1. 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.
  2. Regular recursive lock. If a method has 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM