Singleton design pattern in java

Singleton pattern is one of the commonly used design solution. It describes a technique for ensuring that only a single instance of a class is ever created. In essence, the technique takes the following approach: don’t let anyone outside the class create instances of the class.

Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the Singleton can be easily adjusted to allow more connections.

There are many ways to achieve singleton in java, let us implement all possible approaches with common mistakes with solutions.

Click here for downloading examples source code with JUnit test classes (Github Link)

Example 1: Creating one instance of a subclass only.

If you know the one instance being created will be a subclass, make the parent class abstract and provide a method to get the current instance. An example of this is the Toolkit class in the AWT package. The constructor for Toolkit is public (the default constructor in this particular case):

public Toolkit()

and the class has a getDefaultToolkit() method for getting the specific subclass — in this case, the subclass is platform-specific:

public static Toolkit getDefaultToolkit()

On a Linux platform with the Sun Java runtime, the specific subclass is of type sun.awt.X11.XToolkit. However you don’t need to know that because you only access the class through its common abstract parent class, Toolkit.

Now let us create a sample program to understand singleton to create single instance of child class.

Now suppose we have to operate two methods these are:

  1. keepFileInDefaultDir(File file): copy a file to a fixed directory as per operating system. If operating system is windows then file should be copied in C:\\MyFiles directory.
  2. getAllFilesFromDefaultDir(): we have to get list of files from a fixed directory in which we copied file. As in case of Windows OS we are coping files in C:\\MyFiles directory.
/**
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Holds single instance of a base class.
 *
 * @author SANJAY
 * @see Windows
 * @see Linux
 */
public abstract class Example1 {
	private static Example1 example1 = null;

	/**
	 * constructor.
	 */
	Example1() {
		super();
	}

	/**
	 * As per the Operating system creates a instance of base class. Example: If operating system is Windows then Object will hold Windows class
	 * Instance.
	 *
	 * @return Example1 instance
	 */
	public synchronized static Example1 getDefaultInstance() {
		if (example1 == null) {
			String osName = System.getProperty("os.name");
			if (osName.startsWith("Windows")) {
				example1 = new Windows();
			} else if (osName.startsWith("Linux")) {
				example1 = new Linux();
			}
		}
		return example1;
	}

	/**
	 * Abstract method. Implemented in Linux and Windows class.
	 *
	 * @param file
	 *            : file to create a copy in default directory as per Operating system.
	 * @return boolean: status of copy.
	 * @throws IOException
	 */
	public abstract boolean keepFileInDefaultDir(File file) throws IOException;

	/**
	 * Get's all file from a directory as per Operating system.
	 *
	 * @return List: fileList
	 */
	public abstract List<File> getAllFilesFromDefaultDir();

}

Now you can see in the above Example1 Class is an abstract class so that Object of this class can’t be created.

getDefaultInstance() will return a single object of a subclass as if program is running in Windows operating system then it will return Object of a Windows class and Linux class will never be loaded.

keepFileInDefaultDir(File) In case of windows OS this function will keep the files in C:\\MyFiles Location as per the implementation of Windows class. In Linux OS it will keep file in different location.

getAllFilesFromDefaultDir() It will return list of files from a directory as per child class object. If example1 is holding Windows class object then it will retrieve all files from C:\\MyFiles Location.

Now let’s see the child class implementation.

/**
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * This class will be loaded by Example1 Class if Operating system is Windows.
 *
 * @author SANJAY
 */
final public class Windows extends Example1 {
	/**
	 * Directory to keep and retrieve files in a Windows Operation system.
	 */
	private String defaultDir = "C:\\MyFiles";

	/**
	 * default constructor for restricting object creation outside the package.
	 */
	Windows() {
		super();
	}

	/**
	 * Abstract method. copy a file in a Windows machine "defaultDir".
	 *
	 * @param file
	 *            : file to create a copy in default directory as per Windows system.
	 * @return boolean: status of copy.
	 * @throws IOException
	 */
	@Override
	public boolean keepFileInDefaultDir(File file) throws IOException {
		File myFile = new File(defaultDir);
		myFile.mkdirs();
		myFile = new File(defaultDir, file.getName());
		return myFile.createNewFile();
	}

	/**
	 * Get's all file from a directory in windows operating system.
	 *
	 * @return List: fileList
	 */
	@Override
	public List<File> getAllFilesFromDefaultDir() {
		List<File> fileList = new ArrayList<File>();
		File directory = new File(defaultDir);
		if (!directory.exists()) {
			return null;
		}
		File[] listOfFiles = directory.listFiles();
		for (int i = 0; i < listOfFiles.length; i++) {
			if (listOfFiles[i].isFile()) {
				fileList.add(listOfFiles[i]);
			}
		}
		return fileList;
	}
}

Here you can notice that Windows class is final and its constructor is default in such a way that outside the package object of this class can’t be created.

Same way Linux class can be implemented:

/**
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * This class will be loaded by Example1 Class if Operating system is Linux.
 *
 * @author SANJAY
 */
final public class Linux extends Example1 {

	/**
	 * default constructor for restricting object creation outside the package.
	 */
	Linux() {
		super();
	}

	/**
	 * Abstract method. copy a file in a Linux machine directory.
	 *
	 * @param file
	 *            : file to create a copy in default directory as per Linux system.
	 * @return boolean: status of copy.
	 * @throws IOException
	 */
	@Override
	public boolean keepFileInDefaultDir(File file) {
		// Method Implementation Logic as per Linux Machine
		return true;
	}

	/**
	 * Get's all file from a directory in a Linux Machine.
	 *
	 * @return List: fileList
	 */
	@Override
	public List<File> getAllFilesFromDefaultDir() {
		// Method Implementation Logic as per Linux Machine
		return null;
	}

}

It is very clear that user has to deal with Example1 class only. User has no need to know about Windows and Linux class as logic for object creation of these classes is taken care by Example1 class only.

Example 2: 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.

/**
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * Creates single instance of EagerInitialization class at class loading time.
 *
 * @author SANJAY
 */
public class EagerInitialization {
	/**
	 * Eager Initialization of Object.
	 */
	private static final EagerInitialization INSTANCE = new EagerInitialization();

	/**
	 * Constructor: Outside the class restriction for object creation.
	 */
	private EagerInitialization() {

	}

	/**
	 * @return EagerInitialization INSTANCE : single instance all time.
	 */
	public static EagerInitialization getDefaultInstance() {
		return INSTANCE;
	}

}

Drawback in above implementation: Instance is created irrespective of it is required in runtime or not.
Note: If object doesn’t hold heavy resource then this is the best approach.

Singleton Violation by reflection:
Java Reflection is a very powerful which can easily break singleton. So now let us break singleton class by reflection program.

/**
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.lang.reflect.Constructor;

/**
 * Breaks singleton by creating more than one instance of a singleton class.
 *
 * @author SANJAY
 * @see EagerInitialization
 */
public class ReflectionSingletonViolation {

	/**
	 * Creates two instance of EagerInitialization class by using reflection concept.
	 *
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		EagerInitialization firstOb = EagerInitialization.getDefaultInstance();
		EagerInitialization secondOb = null;
		// reflection concept to get constructor of a EagerInitialization class.
		Constructor<EagerInitialization> constructor = EagerInitialization.class.getDeclaredConstructor();
		// change the accessibility of constructor for outside a class object creation.
		constructor.setAccessible(true);
		// creates object of a class as constructor is accessible now.
		secondOb = constructor.newInstance();
		// close the accessibility of a constructor.
		constructor.setAccessible(false);
		System.out.println("Both Objects are Equal:" + firstOb.equals(secondOb));
		System.out.println("hash code of firstOb: " + firstOb.hashCode());
		System.out.println("hash code of secondOb: " + secondOb.hashCode());
	}

}

Above code clarifies that both objects are now equal as hashCode of both objects are different.
Here is the output of above code:

Both Objects are Equal:false
hash code of firstOb: 12115735
hash code of secondOb: 20876681

Example 3: Enum Reflection Safe Singleton
To avoid the situation of singleton violation by reflection we can use of Enum to implement singleton design pattern as Java ensures that any enum value is instantiated only once in a Java program.

/**
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * enum values are globally accessible, so is the singleton.
 *
 * @author SANJAY
 */
public enum ReflectionSafeSingleton {
	/**
	 * Single instance of enum ReflectionSafeSingleton.
	 */
	SINGLE_INSTANCE;

	/**
	 * Methods same as we creates in class.
	 */
	public void sayHello() {
		System.out.println("Hello");
	}

}

Drawback in above implementation: Instance is created irrespective of it is required in run time or not.

Example 4: Lazy Initialization Singleton
Here the object of a class will be created only once when it is required (i.e. If we are accessing any static field of this class then object won’t be created).
Lazy Initialization concept restricts the creation of instance until requested first time.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * Creates single instance of LazyInitialization class once required only.
 *
 * @author SANJAY
 */
public class LazyInitialization {
	private static volatile LazyInitialization instance = null;

	/**
	 * Constructor: Outside the class restriction for object creation.
	 */
	private LazyInitialization() {

	}

	/**
	 * If multiple thread are calling in single time then singleton violation may occur.
	 *
	 * @return LazyInitialization instance : Single instance all time.
	 */
	public static LazyInitialization getDefaultInstance() {
		if (instance == null) {
			instance = new LazyInitialization();
		}
		return instance;
	}

}

Drawback in above implementation: In case of multithreading multiple instance of class might create. For example suppose two threads are calling getDefaultInstance() method and checking if(instance == null) at the same time then for both threads it will true and both threads will create instance of LazyInitialization class.

Thread Safe Lazy Initialization Singleton
So now let us create a thread safe singleton class.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * Thread safe Lazy initialize singleton class.
 *
 * @author SANJAY
 */
public class ThreadSafeSingleton {
	private static volatile ThreadSafeSingleton instance; 

	/**
	 * private Constructor restrict the object creation outside the class.
	 */
	private ThreadSafeSingleton() {

	}

	/**
	 * Returns singleton object in every situation (in multiple threads calling as well).
	 *
	 * @return ThreadSafeSingleton instance singleton.
	 */
	public static synchronized ThreadSafeSingleton getDefaultInstance() {
		if (instance == null) {
			instance = new ThreadSafeSingleton();
		}
		return instance;
	}
}

Drawback in above implementation: Here getDefaultInstance method is synchronized which will degrade the performance. For example if multiple threads are calling this method to get object then at a time only one thread will enter into the method and other threads has to wait until first thread is not getting object.
So now let us avoid drawback by writing double checked locking lazy initialization singleton code.

Thread Safe Double Checked Locking Lazy Initialization Singleton
Here once the getDefaultInstance method is called that is on the first call (first time object creation), contains of the method will be synchronized and then as object is created once so all the time we will check that if object already exist so return the same object without any locking (i.e. No synchronized contents will execute).

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani.
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * Thread Safe Double Checked Locking Lazy Initialization Singleton.
 *
 * @author SANJAY
 */
public class DoubleCheckedSingleton {
	private static volatile DoubleCheckedSingleton instance;

	/**
	 * Constructor: Outside the class object Creation restriction.
	 */
	private DoubleCheckedSingleton() {

	}

	/**
	 * Double checked locking concept used so that in case of multithreading environment also it will return single object all the time.
	 *
	 * @return DoubleCheckedSingleton instance.
	 */
	public static DoubleCheckedSingleton getDefaultInstance() {
		if (instance == null) {
			synchronized (DoubleCheckedSingleton.class) {
				if (instance == null) {
					instance = new DoubleCheckedSingleton();
				}
			}
		}
		return instance;
	}
}

Note: Here we are checking twice that object is null or not so that in case of multithreading environment also it will return single object all the time. For an example if 4 threads are calling getDefaultInstance method then first it will check that object is null or not if object is not null then all threads will get the same singleton object and no locking will be applied but suppose this time object is not created and all four threads has checked that object is null then in this situation at this time only one thread will enter inside the synchronized block and again check that object exist or not, as this time object is null so one object will be created and this thread will get this object and leave synchronized block now second thread will enter inside the synchronized block and it will check that object exist or not, at this time object exist as it was already created by first thread so at this time rather than creating new instance this second thread will get already existed instance only and the same will happen with remaining two threads as well. So In case of multithreading also it will be singleton only.

Example 5: Singleton using inner class
This is the best approach to create a singleton class by using inner helper class. In this example synchronization in not required even then our class will be thread safe and lazy initialization as well.
In this approach private inner static class contains the instance of the singleton class. When the Singleton class is loaded then static inner class won’t be loaded into memory and only when someone calls the getDefaultInstance method then only this inner class will be loaded and will create outer class instance.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

/**
 * Best approach to create singleton class using inner class, No synchronization required.
 *
 * @author SANJAY
 */
public class SingletonViaInnerClass {
	/**
	 * private Constructor restrict the object creation outside the class.
	 */
	private SingletonViaInnerClass() {

	}

	/**
	 * Inner class as a helper to create Instance of SingletonViaInnerClass.
	 *
	 * @author SANJAY
	 */
	private static class SingletonHelperInnerClass {
		private static final SingletonViaInnerClass INSTANCE = new SingletonViaInnerClass();
	}

	/**
	 * Loads SingletonHelperInnerClass to create instance.
	 *
	 * @return SingletonViaInnerClass instance.
	 */
	public static SingletonViaInnerClass getDefaultInstance() {
		return SingletonHelperInnerClass.INSTANCE;
	}
}

Example 6: Singleton Serialization
Sometimes in distributed systems, we need to implement Serializable interface in Singleton class so that we can transfer singleton object from one component to another component or from one ejb bean to another ejb bean or for storing its state in file system so that we can retrieve it at later point of time. Event it might happen that we want to create a singleton class whose parent class implements Serializable interface in that case also our base (singleton) class will be serializable.
Let us see an example of a singleton class that implements Serializable interface.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.Serializable;

/**
 * Serializable Singleton Class with common mistake.
 *
 * @author SANJAY
 */
public class SerializableSingleton implements Serializable {
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor: Outside the class object Creation restriction.
	 */
	private SerializableSingleton() {

	}

	private static class SerializableSingletonHelper {
		private static final SerializableSingleton INSTANCE = new SerializableSingleton();
	}

	/**
	 * Double checked locking concept used so that in case of multithreading environment also it will return single object all the time.
	 *
	 * @return SerializableSingleton instance.
	 */
	public static SerializableSingleton getDefaultInstance() {
		return SerializableSingletonHelper.INSTANCE;
	}
}

Drawback of above implementation: As class is serializable it means that we can serialize the object of a class and hence once we deserialize the serialized object, it will have different hashcode. What I mean to say is, that by deserializing the object it comes as a different object which means that in this case singleton will be violated.
Let us violate our above code:

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 * Test class for SerializableSingleton.
 *
 * @author SANJAY
 */
public class SerializableSingletonMain {
	/**
	 * @param args
	 * @throws Exception
	 *             instance of : IOException or FileNotFoundException or ClassNotFoundException
	 */
	public static void main(String[] args) throws Exception {
		// first instance of class.
		SerializableSingleton firstInstance = SerializableSingleton.getDefaultInstance();
		// serialize firstInstance in filename.ser file.
		ObjectOutput out = new ObjectOutputStream(new FileOutputStream("myFile.ser"));
		out.writeObject(firstInstance);
		// Close the connection.
		out.close();

		// deserialize myFile.ser file object
		ObjectInput in = new ObjectInputStream(new FileInputStream("myFile.ser"));
		SerializableSingleton secondInstance = (SerializableSingleton) in.readObject();
		// close the connection.
		in.close();

		// Check the equality of firstInstance with secondInstance(deserialized object).
		System.out.println("Both objects are equal: " + firstInstance.equals(secondInstance));
		System.out.println("instanceOne hashCode=" + firstInstance.hashCode());
		System.out.println("instanceTwo hashCode=" + secondInstance.hashCode());
	}
}

Hence we have seen that by deserializing the object, we have violated the singleton.

Both objects are equal: false
instanceOne hashCode=5538765
instanceTwo hashCode=10039797

Implement readResolve() to avoid singleton violation by deserialization.
To avoid the situation of singleton violation by deserialization, let us provide implementation of readResolve() method in our above SerializableSingleton
class.

/*
 * Copyright (C) 2014, 2015 Sanjay Madnani
 *
 * This file is free to use: you can redistribute it and/or modify it under the terms of the
 * GPL General Public License V3 as published by the Free Software Foundation, subject to the following conditions:
 *
 * The above copyright notice should never be changed and should always included wherever this file is used.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
 * See the GNU General Public License for more details.
 *
 */
package com.sanjay.examples.singleton;

import java.io.Serializable;

/**
 * Serializable Singleton Class with common mistake.
 *
 * @author SANJAY
 */
public class SerializableSingleton implements Serializable {
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor: Outside the class object Creation restriction.
	 */
	private SerializableSingleton() {

	}

	/**
	 * Inner class as a helper to create singleton Instance.
	 *
	 * @author SANJAY
	 */
	private static class SerializableSingletonHelper {
		private static final SerializableSingleton INSTANCE = new SerializableSingleton();
	}

	/**
	 * Double checked locking concept used so that in case of multithreading environment also it will return single object all the time.
	 *
	 * @return SerializableSingleton instance.
	 */
	public static SerializableSingleton getDefaultInstance() {
		return SerializableSingletonHelper.INSTANCE;
	}

	/**
	 * Prevent singleton violation by deserialization.
	 *
	 * @return Singleton Instance of class at deserialization.
	 */
	private Object readResolve() {
		return SerializableSingletonHelper.INSTANCE;
	}
}

Note: After this implementation we can test our code using SerializableSingletonMain class of this example 6. So by testing I got following output:

Both objects are equal: true
instanceOne hashCode=10039797
instanceTwo hashCode=10039797

It proves that in case of serialization with singleton, we can implement readResolve()
method to avoid singleton violation by deserialization.

Advertisements

About Sanjay Madnani

Software Developer.
This entry was posted in Tutorials and tagged , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s