Creating a singleton in java

In this post I explain how to create only one object of a java class, then a single instance is available in the application.
An object of this type is called singleton and a starting class can be the following:

public class Singleton {

    private static Singleton instance = null;

    private Singleton() {

    public static synchronized Singleton getInstance() {
	if (instance == null) {
	    instance = new Singleton();
	return instance;

    protected Object clone() throws CloneNotSupportedException {
	throw new CloneNotSupportedException();

Note the following features of the class Singleton:

  • a variable “instance” of type Singleton and with modifier static so it is shared by all instances of the class and already initialized to null even without instances of the class
  • a constructor with modifier private then you can’t call it outside the class; the importance of this constructor is not what does (it does nothing) but the fact that there is, so the java compiler doesn’t create a default public constructor and you can’t create an object Singleton with line code “new Singleton();”
  • a method “getInstance” with modifiers public and static then you can call it outside even without an object Singleton, and it is the only way to create an instance of Singleton, it calls the private constructor if and only if the variable “instance” is null; it has also the modifier synchronized to prevent the access at the same time and avoid the creation of multiple instances
  • the object “Singleton” is created only after the call to “getInstance” that is only when it is requested at the first time; this way is called lazy initialization
  • I put the method “clone”, as described in Introducing the singleton – The Single Java Object
    in this example it is useless because the class Singleton doesn’t implement Cloneable then the method clone throws the exception CloneNotSupportedException anyway;
    its implementation would be important if the class Singleton is extended an other class implementing Cloneable and the method clone too, overriding it again you prevent to copy the object
  • remember that every class extending Singleton doesn’t inherit the variable “instance” because it is private and all constructors even if public


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.