We are creating Singleton WRONG!

Photo by NeONBRAND on Unsplash

Singleton is not something we are handling recently. The concept of Singleton started long back when we started to deal with multiple threads in our program.

From simple methods of creating a singleton (Eager initialization) to advanced methods such as Bill Pugh Singleton Implementation; every method has its own use case, cons, and pros.

Most singleton method is broken with some hack techniques, so we need to have a method that can work perfectly in multithreaded as well as the single-threaded environment.

Let us first explore a simple method to write a singleton class, here is the simplest method we can adopt:

// Java code to create singleton class by Eager Initialisationpublic class Singleton{// public instance initialised when loading the classprivate static final Singleton instance = new Singleton();private Singleton(){   // private constructor}public static Singleton getInstance(){return instance;}}

This method creates a single instance of the class, whether it already exists or not. If the instance already exists then we should not create new object, rather use the existing one.

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the program. Singleton can be used for logging, database objects, caching and thread pool.

The primary goal of the singleton is to have a single instance for every scenario, so I will be using Enum to create singleton behavior. Let us create enum singleton:

public enum EnumSingleton {INSTANCE;}

Here is how you can use that:

//EnumSingleton.javapublic enum EnumSingleton 
String value = "inside"; public String getValue() { return value; } public void setValue(String value) { this.value = value; }}

Let’s use it in our class:

//MyMainClass.javapublic class MyMainClass{
public static void main(String []args){

EnumSingleton singleton = EnumSingleton.INSTANCE
System.out.println("Value 1 :: "+singleton.getValue()); singleton.setValue("android"); System.out.println("Value 2 :: "+singleton.getValue());

Here, is the output:

//output Value 1 :: insideValue 2 :: android

An Enum has the property that only one instance of its value can exist, thereby we can use it for the singleton. Pretty simple!

Also, enums are inherently serializable, we don’t need to implement it with a serializable interface. The reflection problem is also not there. Therefore, it is 100% guaranteed that only one instance of the singleton is present.

Thus, this method is recommended as the best method of making singletons in Java.

Founder at Inside Android | Youtuber | App Developer