Reputation: 337
class Bob {
private static final Object locke = new Object();
private static volatile int value;
public static void fun(){
synchronized(locke){
value++;
}
}
}
How is this different from synchronizing on the class, i.e. synchronized(Bob.class){...}
Upvotes: 13
Views: 141
Reputation: 308169
Some other code can break yours by doing a synchronized(Bob.class)
. If they do, your code suddenly contests with their code for the lock, possibly breaking your code.
That danger is removed if the lock
object is not accessible from outside the object that needs it.
Upvotes: 19