Singleton Design pattern is widely used in different Java frameworks and libraries. Nonetheless, not many of us really know how to implement one. In this post, I will share with you different techniques of creating Java Singleton.
Let’s start with a simple one:
public class SimpleJavaSingleton { // step 1. private constructor private SimpleJavaSingleton() {} //step 2. create instance of a class private final static SimpleJavaSingleton instance = new SimpleJavaSingleton(); //step 3. create method to return this instance public static SimpleJavaSingleton getInstance() { return instance; } }
Step 1. We need to define a private constructor so that nobody could create an instance of a class. That’s why it’s a singleton, it should be only one!
Step 2. Initialize a final instance of a class. That will be returned each time somebody calls it.
Step 3. Define a method that will return instance created in Step 2.
In the example above your singleton will be initialized no matter somebody will call it or not.
Not very optimal, isn’t it? I wanna improve code:
public class SimpleJavaSingleton { private SimpleJavaSingleton() {} private static SimpleJavaSingleton instance; public static SimpleJavaSingleton getInstance() { if (instance == null) { instance = new SimpleJavaSingleton(); } return instance; } }
Notice the difference, we removed final keyword from instance variable and moved the initialization of object to
getInstance() method. With this approach, singleton will be initialized only one time but only when it will be called.
What if our singleton should be thread safe? There is a solution to it and it’s very simple!
public class SimpleJavaSingleton { private SimpleJavaSingleton() {} private static SimpleJavaSingleton instance; public static synchronized SimpleJavaSingleton getInstance() { if (instance == null) { instance = new SimpleJavaSingleton(); } return instance; } }
To solve thread safety issue add synchronized keyword, just like in above code.
Ok, now you think that’s it? No! Imagine there is a new requirement, that our singleton should be serializable.
Fine, we have a solution to that also:
import java.io.Serializable; public class SimpleJavaSingleton implements Serializable { private static final long serialVersionUID = 1234567890L; private SimpleJavaSingleton() {} private static SimpleJavaSingleton instance; public static synchronized SimpleJavaSingleton getInstance() { if (instance == null) { instance = new SimpleJavaSingleton(); } return instance; } }
Nice, we did all we can to this singleton class, but it looks ugly.
Can we make it simpler? Yes!
public enum MyEnumSingleton { INSTANCE; private String singleton = "enum singleton"; public String getInstance() { return singleton; } }
The code above is thread-safe and serializable out of the box.
I used String as an instance to return, but you can change it to any other class of your choice.
Thanks for reading!