Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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){...}

like image 516
Binary Bob Avatar asked Jun 19 '13 20:06

Binary Bob


People also ask

What are the advantages of using a lock instead of synchronization?

In synchronisation, if a thread is waiting for another thread, then the waiting thread won't do any other activity which doesn't require lock access but with lock interface there is a trylock() method with which you can try for access the lock and if you don't get the lock you can perform other alternate tasks.

Should static method be synchronized?

The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method. The Thread will acquire a class level lock of a java class, such that only one thread can act on the static synchronized method.

Why do we need static synchronization in Java?

The intended purpose of static synchronized methods is when you want to allow only one thread at a time to use some mutable state stored in static variables of a class. Nowadays, Java has more powerful concurrency features, in java. util.

Can we use synchronized for static class?

If a static method is synchronized, the lock is done on the class object. So that method as well as any other static methods can't be executed when the first static synchronized method is getting executed.


1 Answers

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.

like image 170
Joachim Sauer Avatar answered Sep 28 '22 23:09

Joachim Sauer