I would like to put some light on singleton design pattern.
Your First Code Snippet
public class MyClass {
private final static MyClass myClass = new MyClass();
public static MyClass getInstance() {
return myClass;
}
}
The above approach works fine but has drawback as instance is getting created much before actually it is required so at run-time think of the situation that if the instance is not big you can keep it if it is unused but if it big then what is the purpose of creating the instance.This approach is called Eager initialization
The code shown below indicates the second approach called Lazy initialization
public class MyClass {
private final static MyClass myClass;
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}
But here again there is one drawback in your code,let's understand the defect in the above code
Let's consider we have tow threads namely T1 and T2 and both threads are intended to create the instance and executes the check null == myClass,now both threads have identified instance variable to null thus assume they must create an instance. They sequentially goes to synchronized block and create the instances. At the end, we have two instances in our application.
This can be resolved by simply double check locking. Below code will show you the better way of implementation. Just note- I have used private constructor in code.
public class MyClass {
private final static MyClass myClass = null;
//private constructor
private MyClass(){
}
public static MyClass getInstance() {
if(myClass == null) {
synchronized (MyClass.class){
// Double check
if(myClass == null){
myClass = new MyClass();
}
}
}
return myClass;
}
}