I was reading Synchronized working. Here is the example:
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
Let Suppose two Thread A and B are accessing getInstance(); method,
If thread A is in synchronized block then thread B will skip that block and execute next block/statement or will wait/blocked until Thread A leave the synchronized block.
2nd What is, why is Singleton.class in synchronized parameter and when it could be null
and the below Statement is true?
Intrinsic locks are on the object:
class A { public synchronized void method1(){...} public synchronized void method2(){...} }If thread A is in
method1thenthreadBcannot entermethod2or any other synchronized method .
If thread A is in method1 then threadB cannot enter method2 or any other synchronized method .