I have some coding like this.
public class WaitTest {
public static void main(String[] args) {
Object object = new Object();
try {
synchronized (object) {
object.wait(5000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Does using synchronized (object) means WaitTest class is owning the monitor of object?
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.
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.
Classes don't own monitors, threads do.
In your example, WaitTest
doesn't own the monitor, the main thread does.
In particular, no other thread would be able to enter a synchronized
block on the same object, including calling any of the object
's synchronized
methods, if it had any such methods.
The thread owns the monitor, and there are three ways to own the monitor, according to the official JDK doc here: Object.notify
A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a synchronized statement that synchronizes on the object.
- For objects of type Class, by executing a synchronized static method of that class.
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