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

1

6

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.

Aorta answered 8/3, 2015 at 21:27 Comment(0)
I
6

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.

Indus answered 8/3, 2015 at 21:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.