Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 980
DuZhentong Avatar asked Apr 02 '18 11:04

DuZhentong


People also ask

What is the difference between lock and monitor?

Answer: Lock Vs Monitor in C# multithreading: Difference between monitor and lock in C# is that lock internally wraps the Enter and Exit methods in a try… finally block with exception handling. Whereas for Monitor class in C#, we use try and finally block explicitly to release lock properly.

What is a monitor in Java?

Monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signaling other threads that their condition has been met. It is an entity that possesses both a lock and a wait set.

What does lock mean Java?

Simply put, a lock is a more flexible and sophisticated thread synchronization mechanism than the standard synchronized block. The Lock interface has been around since Java 1.5. It's defined inside the java. util. concurrent.

What is the difference between monitor lock and mutex?

The monitor lock only exist inside a single process, while the Mutex -lock is machine wide. So a monitor lock is appropriate for making objects and data-structures thread safe, but not for providing system-wide exclusive access to say a file or device.


1 Answers

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.

like image 76
Harsh Mehta Avatar answered Sep 22 '22 06:09

Harsh Mehta