Synchronized static method vs synchronize class object

Suppose my Foo class looked like this:

 public class Foo { public static void func_1() { /* do something */ } public static void func_2() { /* do something */ } } 

and that the Bar class looked like this:

 public class Bar { public void method_1() { synchronized(Foo.class) { Foo.func_1(); } } } 

Now instead of locking the Foo.class object in Bar.method_1 , can I declare Foo.func_1 and Foo.func_2 as synchronized and still archive the same target?

thanks

+4
source share
3 answers

Yes, they accomplish the same thing: blocking Foo.class . Here is the relevant excerpt from the Java Language Specification, section 8.4.3.6 :

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

Using synchronized for the static methods func_1() or func_2() in your Foo class implicitly blocks Foo.class , and synchronized(Foo.class) blocks it explicitly.

+2
source

The static synchronized method gets locked by class and, by locking on Foo.class , you do the same. So yes, they will achieve the same.

+2
source

Yes, they are almost the same. The only difference: in one case, the lock is acquired before the method is called, and in the other, later.

0
source

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


All Articles