출처 : http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/
Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition. It has been debated long enough in java community regarding possible approaches to make any class singleton. Still, you will find people not satisfied with any solution you give. They can not be overruled either. In this post, we will discuss some good approaches and will work towards our best possible effort.
Sections in this post:
- Eager initialization
- Lazy initialization
- Static block initialization
- Bill pugh solution
- Using Enum
- Adding readResolve()
- Adding serial version id
- Conclusion
Singleton term is derived from its mathematical counterpart. It wants us, as said above, to have only one instance. Lets see the possible solutions:
Eager initialization
This is a design pattern where an instance of a class is created much before it is actually required. Mostly it is done on system start up. In singleton pattern, it refers to create the singleton instance irrespective of whether any other class actually asked for its instance or not.
public class EagerSingleton { private static volatile EagerSingleton instance = new EagerSingleton();
// private constructor private EagerSingleton() { }
public synchronized static EagerSingleton getInstance() { if (instance == null) { instance = new EagerSingleton(); } return instance; } } |
Above method works fine, but has one performance drawback. The getInstance() method is synchronized and each call will require extra locking/unlocking steps which are necessary only for first time, and never there after.
Lets solve above problem in next method.
Lazy initialization
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. In singleton pattern, it restricts the creation of instance until requested first time. Lets see in code:
public final class LazySingleton { private static volatile LazySingleton instance = null;
// private constructor private LazySingleton() { }
public static LazySingleton getInstance() { if (instance == null) { synchronized (LazySingleton.class) { instance = new LazySingleton(); } } return instance; } } |
On first invocation, above method will check if instance is already created using instance variable. If there is no instance i.e. instance is null, it will create an instance and will return its reference. If instance is already created, it will simply return the reference of instance.
But, this method also has its own drawbacks. Lets see how. Suppose there are two threads T1 and T2. Both comes to create instance and execute “instance==null”, 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 error can be solved using double-checked locking. This principle tells us to recheck the instance variable again in synchronized block in given below way:
Please ensure to use “volatile” keyword with instance variable otherwise you can run into out of order write error scenario, where reference of instance is returned before actually the object is constructed i.e. JVM has only allocated the memory and constructor code is still not executed. In this case, your other thread, which refer to uninitialized object may throw null pointer exception and can even crash the whole application.
Static block initialization
If you have little idea about class loading sequence, you can connect to the fact that static blocks are executed during the loading of class and even before the constructor is called. We can use this feature in our singleton pattern also like this:
public class StaticBlockSingleton { private static final StaticBlockSingleton INSTANCE;
static { try { INSTANCE = new StaticBlockSingleton(); } catch (Exception e) { throw new RuntimeException("Uffff, i was not expecting this!", e); } }
public static StaticBlockSingleton getInstance() { return INSTANCE; }
private StaticBlockSingleton() { // ... } } |
Above code has one drawback. Suppose there are 5 static fields in class and application code needs to access only 2 or 3, for which instance creation is not required at all. So, if we use this static initialization. we will have one instance created though we require it or not.
Next section will overcome this problem.
Bill pugh solution
Bill pugh was main force behind java memory model changes. His principle “Initialization-on-demand holder idiom” also uses static block but in different way. It suggest to use static inner class.
Using Enum
This type of implementation recommend the use of enum. Enum, as written in java docs, provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.
Adding readResolve()
So, till now you must have taken your decision that how you would like to implement your singleton. Now lets see other problems that may arise even in interviews also.
Lets say your application is distributed and it frequently serialize the objects in file system, only to read them later when required. Please note that, de-serialization always creates a new instance. Lets understand using an example:
Our singleton class is:
public class DemoSingleton implements Serializable { private volatile static DemoSingleton instance = null;
public static DemoSingleton getInstance() { if (instance == null) { instance = new DemoSingleton(); } return instance; }
protected Object readResolve() { return instance; }
private int i = 10;
public int getI() { return i; }
public void setI(int i) { this.i = i; } } |
Now when you execute the class SerializationTest, it will give you correct output.
Adding serial version id
So far so good. Till now, we have solved the problem of synchronization and serialization both. Now, we are just one step behind our correct and complete implementation. And missing part is serial version id.
This is required in condition when you class structure can change in between you serialize the instance and go again to de-serialize it. Changed structure of class will cause JVM to give exception while de-serializing process.
Conclusion
After having discussed so many possible approaches and other possible error cases, i will recommend you below code template to design your singleton class which shall ensure only one instance of class in whole application in all above discussed scenarios.
Happy Learning !!
Update: I just thought to add some examples which can be referred for further study and mention in interviews:
========================================================================================================
========================================================================================================
Singleton Serializable
출처 : http://atin.tistory.com/355
자바 개발을 하면서 제일 많이 쓰는 패턴 중 하나가 싱글톤 패턴이다.
그리고 싱글톤 소스 또한 다양하게 작성한다.
Source2와 같은 경우는 다중 쓰레드 상에서 위험하다. Source3과 같은 경우는 안전하긴 하지만 성능상 Source1이 제일 좋다.
Source4와 같은 경우는 싱글톤에서 직렬화 처리를 해주기 위한 방법이다. Serializable 을 구현해주고 readResolve메소드를 구현하고 모든 인스턴스 필드를 transient 로 선언해준다.
Source5와 같은 경우는 enum을 통한 구현 방법이다. 직렬화가 자동으로 지원되고 인스턴스가 여러개 생기지 않도록 지원해준다.
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){}
public static final Singleton getInstance(){
return instance;
}
class Singleton2 {
private static Singleton2 instance = null;
private Singleton2(){}
public static final Singleton2 getInstance(){
if(instance == null) instance = new Singleton2();
return instance;
}
}
[Source. 2]
class Singleton3 {
private static Singleton3 instance = null;
private Singleton3(){}
public static final Singleton3 getInstance(){
if(instance == null) {
synchronized(Singleton3.class){
instance = new Singleton3();
}
}
return instance;
}
class Singleton4
implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6209266452691660409L;
private static final transient Singleton4 instance = new Singleton4();
private Singleton4(){}
public static final Singleton4 getInstance(){
return instance;
}
private Object readResolve(){
return instance;
}
instance;
public void method(){}