10
3
|
When reading articles about java thread, I often notice the expression: "current thread is the owner of this object's monitor.". I catch the meaning: the thread gets the right to operate on the object. But I am puzzled why use the phrase "the object's monitor" instend of "the object's lock"? In brief, I don't konw the meaning of word 'monitor' The question may be strange and simple. But wish anybody can help to solve it. 3ks
| |||
add comment |
5
|
See ulmangt's answer for links that explain the term "monitor" as used in this context.
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.
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.
| ||||||||||||||||||||
|
6
|
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:
If you scroll down, it's even got a section explicitly about Java.
| ||
add comment |
1
1
|
I read this in Java language Spec 17.1:
Why necessarily? Doesn't that make java object too heavy weight? I've no idea why a Object like, say, a string, should be naturally a monitor!
EDIT:
I think it over and yes, Java has a keyword synchronized, because EVERY object could have a synchronized method, so it's necessary to associate EVERY object a Monitor.
But still this seems not a very good solution, usually you need more that one mutex for one class, except for that pojo classes that's really very simple.
| ||||||||
|
2
|
Your fundamental problem is in assuming that every object has some sort of
Monitor built into it, waiting for it to be used by some code. In reality, most objects are never used as a monitor, so the monitors don't have to be created until they are used. Rather than implementing this feature as every object having a private Monitor monitor field, think of it as being implemented as the JVM having a global HashMap .
A possible implementation is this: Whenever a
synchronized block is entered, the JVM looks up the synchronized object in the map (monitors ). If it finds it, it gets the monitor to use. If it doesn't find it, it enters a critical section dedicated to the map. It then looks up the object again because another thread may have created it between the previous check and entering the critical section. If it's still not there, it creates the monitor for the synchronized object and leaves the critical section. |