Synchronized Static Methods

If I have a class with several synchronized methods, some of them are static and some of them are not:

public class A { public static void synchronized f1() {} public void synchronized f2() {} } 

what happens when one thread calls f1 () and a second call to f2 (), this means how they synchronize with each other. and what happens if one protector calls f1 () and f1 () calls f2 () ???

+4
source share
3 answers

They are not synchronized with each other at all. The static method synchronizes on A.class , the second synchronizes on this . So this is (almost) as if you wrote:

 public class A { public static void f1() { synchronized(A.class) { ... } } public void f2() { synchronized(this) { ... } } } 

and what happens if one protector calls f1 () and f1 () calls f2 ()

Then this thread will own both monitors during f2 . You must be careful before doing this, as if you pulled the locks in reverse order elsewhere, you will get a dead end.

Personally, I would strongly recommend that you completely eliminate synchronous methods. Instead, synchronize on closed end fields that are only used for locking. This means that only your class can acquire the appropriate monitors, so you can talk more carefully about what happens during the lock and avoid deadlocks, etc.

+9
source

The synchronized static method synchronizes the class object, not the instance.

f1() and f2() can be called by two separate threads and will be executed simultaneously.

See: http://java.sun.com/docs/books/jls/third_edition/html/classes.html#260369

+1
source

The synchronized static method is synchronized with the class of the corresponding class object, so it is different from locking than the one used by instance methods. Obviously, the static method does not have access to this . Thus, your methods f1 () and f2 () are not synchronized with each other, but only against other static or other class instance methods.

+1
source

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


All Articles