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

DuZhentong picture DuZhentong · Apr 2, 2018 · Viewed 9k times · Source

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?

Answer

Harsh Mehta picture Harsh Mehta · Apr 2, 2018

From the official documentation of Locks and Synchronization:

  • Synchronization is built around an internal entity known as the intrinsic lock or monitor lock. (The API specification often refers to this entity simply as a "monitor.")
  • 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 complementary to each other. Every object in Java is associated with a monitor which a thread can lock or unlock.