简体   繁体   中英

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, ie synchronized(Bob.class){...}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM