Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronization: Why is it preferred to lock a private final static object instead of the class's class object?

Simple question:

Why would this be preferred:

public class Foo {

    final private static Object foo = new Object();

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

over this:

public class Foo {

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

or this:

public class Foo {

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

?

To me these all look essentially identical, so I'm not sure what would be the best way to synchronize access to static fields, or why one would be better than another, but I've heard the first is often preferred.

like image 829
Joseph Nields Avatar asked Mar 08 '15 21:03

Joseph Nields


Video Answer


1 Answers

This is about encapsulation. If you're locking on a private field, no other code can lock on the same object. If you're locking on the class object or an instance, any other code in the system that has access to instances of your class can also lock on the same object, introducing unexpected synchronization issues such as deadlocks caused by lock ordering violations.

like image 177
yole Avatar answered Oct 17 '22 02:10

yole