Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How a static synchronized function works? [duplicate]

When a Java member needs to be thread-safe, we do like the following:

 public synchronized void func() {
     ...
 }

This syntax equivalent to:

 public void func() {
      synchronized(this) {
           ....
      }
 }

That is, it actually uses this for a lock.

My question is, if I use synchronized with a static method, as follows:

class AA {
    private AA() {}

    public static synchronized AA getInstance() {
        static AA obj = new AA();
        return obj;
    }
}

In this case, on what is the lock made for the synchronized method?

like image 477
TieDad Avatar asked Jul 16 '13 05:07

TieDad


People also ask

What happens when static method is synchronized?

Static Synchronized method is also a method of synchronizing a method in java such that no two threads can act simultaneously static upon the synchronized method. The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.

Can two threads at same time execute two different methods one is static synchronized and second is only synchronized method?

Indeed, it is not possible! Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.

What will happen if a synchronized method is called by two threads?

Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.

Can two threads call two different synchronized methods of the same class?

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.


2 Answers

In case of static synchronized method, the class object of your class AA will be implicit lock

its equivalent to

class AA {
    private AA() {}

    public static AA getInstance() {
        synchronized(AA.class) {
           AA obj = new AA();
           return obj;
        }
    }
}
like image 124
sanbhat Avatar answered Sep 28 '22 20:09

sanbhat


From section 8.4.3.6 of the JLS:

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

So your code acquires the monitor for AA.class. As sanbhat says, it's like

synchronized(AA.class) {
    ...
}

... just as with an instance method it would be

synchronized(this) {
    ...
}
like image 37
Jon Skeet Avatar answered Sep 28 '22 18:09

Jon Skeet