Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to own the object's monitor

Tags:

java

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?

like image 915
Mawia Avatar asked Mar 06 '13 08:03

Mawia


People also ask

What is object's monitor in Java?

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.

What is the purpose of acquiring an object's monitor by using a synchronized object?

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.


2 Answers

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.

like image 98
NPE Avatar answered Sep 21 '22 13:09

NPE


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.
like image 33
ibic Avatar answered Sep 19 '22 13:09

ibic