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