Java Design Pattern – Singleton Pattern

Singleton Pattern is a design pattern which you often meet in almost applications. Singleton Pattern provides a way to instantiate only one instance in an application context.

The tutorial introduces the design of Singleton Design Pattern and give many ways to create a Singleton Pattern in your application.

I. Technology

– Java 8
– Eclipse: Version: Mars.2 Release (4.5.2)

II. Overview for Java – Singleton Pattern

Technical for creating Single Pattern:
– Create a private static variable of Singleton class. This is the only Instance of Singleton Class.
– Create private constructor for making sure outer class can NOT instantiate object form Singleton Class.
– Create a global method for get Singleton Instance.
java design pattern singleton pattern

Project Structure:
java design pattern project

III. Practices
1. Create a Singleton Class
public class Singleton {
	private String message;
	
	/*
	 * Singleton Instance
	 */
	private static final Singleton instance = new Singleton();
	
	/*
	 * private Constructor for Singleton Pattern
	 * so the class can Not be instantiate
	 */
	private Singleton(){
		message = "Hello World!";
	}
	
	public static Singleton getInstance(){
		return instance;
	}

	public void showMessage() {
		System.out.println(message);
	}

	public void setMessage(String message) {
		this.message = message;
	} 
}
2. Create Main class
public class Main {
	public static void main(String[] args) {
		Singleton singleton = Singleton.getInstance();
		singleton.showMessage();
		singleton.setMessage("New message");
		Singleton newSingletonPointer = Singleton.getInstance();
		newSingletonPointer.showMessage();
	}
}
3. Run & Result

Message from Main Class

Hello World!
New message

Conclusion: singleton and newSingletonPointer is the same instance.

IV. How many ways to implement Singleton Pattern
1. Eager Singleton Pattern

The Eager Singleton pattern is simple way, the Singleton Instance will be created at the class loading time.
Disadvantage is that the instance is created but application maybe NOT use it right after creating time.

public class EagerSingleton {
	private static EagerSingleton instance = new EagerSingleton();
	
	public static EagerSingleton getInstance(){
		return instance;
	}	
}
2. Static Block Singleton Implementation

The Static Block Singleton Implementation is same Eager Singleton Implementation, Instance is created at the Class loading time.

public class StaticBlockSingleton {
	
	private static StaticBlockSingleton instance;
	
	private StaticBlockSingleton(){};
	
	static{
		try{
			instance = new StaticBlockSingleton();
		}catch(Exception e){
			throw new RuntimeException("Exception Error when creating Static Blocking Singleton!");
		}
	}
	
	public static StaticBlockSingleton getInstance(){
		return instance;
	}
}
3. Lazy Singleton Implementation

Lazy Singleton Implementation will create Singleton Instance at the first time of Client call.

public class LazySingleton {
	private static LazySingleton instance;
	
	public static LazySingleton getInstance(){
		if(null == instance){
			instance = new LazySingleton();
		}
		return instance;
	}
}
4. Thread Safe Singleton Pattern

The lazy singleton implementation does NOT adapt with multi-threading programming environment. So thread safe Singleton implementation will help us:

public class ThreadSafeSingleton {
	private static ThreadSafeSingleton instance;
	
	private ThreadSafeSingleton() {}
	
	public static synchronized ThreadSafeSingleton getInstance(){
		if(instance == null){
			instance = new ThreadSafeSingleton();
		}
		return instance;
	}
}

With implementation above, the synchronized lock is always checked, it makes down up performance. Double Checking Implementation below will resolve the problem.

public class ThreadSafeSingleton {
	private static ThreadSafeSingleton instance;
	
	private ThreadSafeSingleton() {}
	
	/**
	 * For improve performance, implement with DoubleLocking
	 */
	public static ThreadSafeSingleton getInstanceDoubleLocking(){
		if(instance == null){
			synchronized (ThreadSafeSingleton.class) {
				if(instance == null){
					instance = new ThreadSafeSingleton();	
				}	
			}
		}
		return instance;
	}
}
5. Bill Pugh Singleton Pattern

Prior 5, Java memory model has lots of issues when having too many threads trying to get Instance, so Bill Pugh gives a new approach:

public class BillPughSingleton {
	
	private BillPughSingleton(){}
    
    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }
    
    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}
6. Enum Singleton Pattern

Java Reflection to destroy Singleton Pattern as Example:

import java.lang.reflect.Constructor;

public class ReflectionSingletonTest {

    public static void main(String[] args) {
        EagerInitializedSingleton instanceOne = EagerInitializedSingleton.getInstance();
        EagerInitializedSingleton instanceTwo = null;
        try {
            Constructor[] constructors = EagerInitializedSingleton.class.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                instanceTwo = (EagerInitializedSingleton) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(instanceOne.hashCode());
        System.out.println(instanceTwo.hashCode());
    }

}

instanceOne.hashCode() is difference instanceTwo.hashCode() because they are two difference instances. Java Reflection is a powerful tool used by many framework as: Spring Framework, Hibernate Framework.

So, to overcome problems above, Enum Singleton Implementation is a good solution:

public enum EnumSingleton {
	
    INSTANCE;
    
    public static void process(){
        // process
    }
}
V. Sourcecode

java singleton pattern

6 thoughts on “Java Design Pattern – Singleton Pattern”

Leave a Reply

Your email address will not be published. Required fields are marked *