When reading articles about Java threads, I often notice the expression: "current thread is the owner of this object's monitor". I get the meaning: the thread gets the right to operate on the object. But I am puzzled why we use the phrase "the object's monitor" instead of "the object's lock"?
In brief, I don't know the meaning of the word 'monitor' The question may be strange and simple. But I wish anybody can help to solve it. 3ks
It is an entity that possesses both a lock and a wait set. In Java, any Object can serve as a monitor. In the Java virtual machine, every object and class is logically associated with a monitor.
In Java there is no keyword to directly create a monitor. To implement a monitor, you must create a new class and use Lock and Condition classes. Lock is the interface is ReentrantLock is the main used implementation, this is the one that we'll learn to use in the current post.
Java Synchronized Method Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.
but I am puzzled why use word "the object's monitor" instend of "the object's lock"?
See ulmangt's answer for links that explain the term "monitor" as used in this context. Note that:
"Monitors were invented by Per Brinch Hansen and C. A. R. Hoare, and were first implemented in Brinch Hansen's Concurrent Pascal language."
(Source: Wikipedia)
Why use the term "monitor" rather than "lock"? Well strictly speaking, the terms do mean different things ... especially if you use them in the way that they were originally intended to be used.
A "lock" is something with acquire and release primitives that maintain certain lock properties; e.g. exclusive use or single writer / multiple reader.
A "monitor" is a mechanism that ensures that only one thread can be executing a given section (or sections) of code at any given time. This can be implemented using a lock (and "condition variables" that allow threads to wait for or send notifications to other threads that the condition is fulfilled), but it is more than just a lock. Indeed, in the Java case, the actual lock used by a monitor is not directly accessible. (You just can't say "Object.lock()" to prevent other threads from acquiring it ... like you can with a Java Lock
instance.)
In short, if one were to be pedantic "monitor" is actually a better term than "lock" for characterizing what Java is providing. But in practice, both terms are used almost interchangeably.
A monitor is simply a term for an object whose methods can be safely used in a multithreaded environment.
There's a great Wikipedia article on Monitors:
http://en.wikipedia.org/wiki/Monitor_(synchronization)
If you scroll down, it's even got a section explicitly about Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With