Synchronization. Why is it preferable to lock a closed destination static object instead of an object of a class class?

Simple question:

Why would this be preferable:

public class Foo { final private static Object foo = new Object(); public static void doSomething() { synchronized(Foo.foo) { //code } } } 

above this:

 public class Foo { public static void doSomething() { synchronized(Foo.class) { //code } } } 

or that:

 public class Foo { public synchronized static void doSomething() { //code } } 

?

For me, these all look essentially the same, so I'm not sure what would be the best way to synchronize access to static fields, or why one would be better than the other, but I heard that the former is often preferable.

+6
source share
1 answer

This applies to encapsulation. If you block a private field, no other code can block the same object. If you lock a class object or instance, any other code on the system that has access to instances of your class can also block the same object, presenting unexpected synchronization problems, such as deadlocks caused by blocking violations.

+6
source

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


All Articles