is now
Showing posts with label Singleton. Show all posts

This post is about Singleton Design pattern in java. All of us may know, there are different way to create singleton instance of class. I am going to write one of them. How we can make singleton object. But before going further, we will first learn what singleton is?

What is Singleton?

Singleton is design pattern which comes under creational pattern. Sometimes, it is important to have one instance of class or we can say, it provide single global entry point to the object.

How we can create Singleton?

There are many ways to create Singleton. Each one of them have their pros and cons. Today, we will discuss how to create Singleton with lazy Initialization with SingletonInstanceHolder class.

package singleton;

public class Singleton {
 private static class SingletonInstanceHolder {
  private static int MODCOUNT = 0;
  private static Singleton INSTANCE = null;
  private static final Object MUTEX = new Object();
   if (INSTANCE == null)
    synchronized (MUTEX) {
     if (INSTANCE == null)
      try {
       INSTANCE = new Singleton();
      } catch (IllegalAccessException e) {
       // TODO Auto-generated catch block
 private Singleton() throws IllegalAccessException {
  if(SingletonInstanceHolder.MODCOUNT > 0)
   throw new IllegalAccessException("Multiple instance"); 

 public static final Singleton getInstance() {
  return SingletonInstanceHolder.INSTANCE;
 // Avoiding duplicate objects with serialization
 public Object readResolve() {
  return getInstance();

The above mentioned class Singleton. This class can't have multiple objects even using reflection api because our code will throw exception if more than one instance is created with reflection.

package singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SingletonTest {
  public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, InstantiationException,
     IllegalAccessException, IllegalArgumentException,InvocationTargetException {
  Class demo = Class.forName("singleton.Singleton");
  Constructor con = demo.getDeclaredConstructor();
  for(int i=0; i<10; i++) {
   Singleton s1 = (Singleton) con.newInstance();

The above code when run will throw following exception. It shows that the Singleton class's object will be created only once and then it will throw exception if tried to called constructor multiple times even with reflection.

Exception in thread "main" java.lang.reflect.InvocationTargetException
 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
 at sun.reflect.NativeConstructorAccessorImpl.newInstance(
 at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(
 at java.lang.reflect.Constructor.newInstance(
 at singleton.SingletonTest.main(
Caused by: java.lang.IllegalAccessException: Multiple instance
 at singleton.Singleton.<init>(
 ... 5 more