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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With