The main reason that this class is thread-safe is because there are no resources in this class which can be shared among multiple threads. For example instance variables.
This class is singleton as JVM will create only single object for this class when the class is loaded by calling mySingletonClass.getInstance()
first time.
Now every time this method is called same instance
will be returned. But now consider the following scenario:
public class mySingletonClass{
int x;
public vois setX(int x){
this.x = x;
}
public int getX(){
return x;
}
private static mySingletonClass INSTANCE = new mySingletonClass();
private mySingletonClass()
{
super();
}
public static mySingletonClass getInstance()
{
return INSTANCE;
}
}
Now there is an instance variable x
. Now since this class is singleton so same object will be shared among multiple threads and that means same instance variable x
. Now you can't be sure that the different threads are accessing the correct value of x
. Then you have to use different ways so that at a time only one thread accesses the shared resources which is x
in the above case. For that you can either make the setX(int x) and getX()
method synchronized
or can create an object LOCK
which will ensure that at a time only one thread mutate the variable x
.