Search code examples
javamultithreadingjvm-hotspot

What is a `monitor` in JVM(Hotspot), a specific object?


In Java Language Spec, Section 17.1: Synchronization, it says

Each object in Java is associated with a monitor, which a thread can lock or unlock.

Section 17.2:

Every object, in addition to having an associated monitor, has an associated wait set. A wait set is a set of threads.

When an object is first created, its wait set is empty. Elementary actions that add threads to and remove threads from wait sets are atomic. Wait sets are manipulated solely through the methods Object.wait, Object.notify, and Object.notifyAll.

A question here is, what is monitor, seems it is an object which contain a wait set?

I have take a look at a similar question What's a monitor in Java? on stackoverflow, but the answers were not so clearly.

A monitor is mechanism to control concurrent access to an object.

A monitor is an entity that possesses both a lock and a wait set. In Java, any Object can serve as a monitor.

I got some more info on Hotspot runtime overview

Per-object synchronization state is encoded in the first word (the so-called mark word) of the VM's object representation. For several states, the mark word is multiplexed to point to additional synchronization metadata. (As an aside, in addition, the mark word is also multiplexed to contain GC age data, and the object's identity hashCode value.) The states are:

  • Neutral: Unlocked

  • Biased: Locked/Unlocked + Unshared

  • Stack-Locked: Locked + Shared but uncontended The mark points to displaced mark word on the owner thread's stack.

  • Inflated: Locked/Unlocked + Shared and contended Threads are blocked in monitorenter or wait(). The mark points to heavy-weight "objectmonitor" structure.[8]

I guess if a monitor is a objectmonitor structure? But objectmonitor does not created at first, only used when heavy weight lock is used due to contention.


Solution

  • A monitor is a concept on which you can perform certain operations. Anything that implements the abstract operations of the concept of a monitor is a good implementation.

    The concept is implemented in HotSpot in the mark word plus everything described in the text that you quoted about the mark word. It is not a single data structure.