Binary Bob
Binary Bob

Reputation: 337

Why synchronize on a static lock member rather than on a class?

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

Answers (1)

Joachim Sauer
Joachim Sauer

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

Related Questions