How does a static synchronized function work?

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

public synchronized void func() { ... } 

This syntax is equivalent to:

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

That is, it actually uses this to block.

My question is: if I use synchronized using the static method as follows:

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

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

+6
source share
3 answers

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

its equivalent

 class AA { private AA() {} public static AA getInstance() { synchronized(AA.class) { AA obj = new AA(); return obj; } } } 
+13
source

From section 8.4.3.6 JLS :

The synchronized method receives the monitor (ยง17.1) before executing it.

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

This way your code gets a monitor for AA.class . As the sanbhat says, like it

 synchronized(AA.class) { ... } 

... just like with the instance method, it will

 synchronized(this) { ... } 
+7
source

He worked on locking AA.class.

 public static AA getInstance() { synchronized(AA.class){ static AA obj = new AA(); return obj; } } 
0
source

Source: https://habr.com/ru/post/949520/


All Articles