In Java, what is the difference between a monitor and a lock

DuZhentong :

Using the synchronized keyword method, using the javap command to view the bytecode, it is found that monitor is used, and if it is possible to call the monitor when the synchronized is implemented, is that my understanding, right? Please correct it if you do not. What is the relationship between them? What is the relationship between the lock and the monitor?

Harsh Mehta :

From the official documentation of Locks and Synchronization(https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html):

  • Synchronization is built around an internal entity known as the intrinsic lock or monitor lock.
  • Every object has an intrinsic lock associated with it. By convention, a thread has to acquire the object's monitor lock before accessing them, and then release the monitor lock when it's done with them. A thread is said to own the lock between the time it has acquired the lock and released the lock. As long as a thread owns a monitor lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
  • When a thread releases the lock, a happens-before relationship is established between that action and any subsequent acquisition of the same lock.

So a monitor and a lock can not be compared for differences, rather they are complimentary to each other. Every object in Java is associated with a monitor which a thread can lock or unlock.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=435812&siteId=1