Java Programming Tutorials

Java programming tutorials with many code examples!

Java Singleton – static final implementation

Java Singleton – static final implementation

It is the simplest and most common implementation of Singleton Design Pattern in Java. In this post we’ll show how to implement it correctly and explain why it works.

How the implementation works

The static final implementation works, because static fields are guaranteed to be initialized once and only once on the first access to the class. So the object to be singleton will be instantiated only once, thusly:

public class SingleObject {

    private static final SingleObject INSTANCE = new SingleObject();

    private SingleObject() {
        System.out.println("Instantiating SingleObject...");
    }
}

When to use

  • To implement a Null Object pattern (unchangeable, default object): Noop Logger, end of Chain of Responsibility, tree root, etc.
  • Singleton object is small and easy to instantiate

Pros and cons

  • simple,
  • thread-safe,
  • initialized only on the firt access to the class,
  • (con) initialized on any access to class (Even when non-singleton field is used), but, in practice, it’s never a problem.

Complete example

The class containing a Singleton Object:

package com.farenda.patterns.singleton;

public class SingleObject {

    // optionally make public and remove the getter
    private static final SingleObject INSTANCE = new SingleObject();

    private SingleObject() {
        System.out.println("Instantiating SingleObject...");
    }

    public static SingleObject getInstance() {
        return INSTANCE;
    }
}

Note that equally well the static field could be also located in some other class – it doesn’t have to be in the Singleton object itself.

Now, the use of the Singleton:

package com.farenda.patterns.singleton;

public class StaticFinalExample {

    public static void main(String[] args) {
        if (SingleObject.getInstance() == SingleObject.getInstance()) {
            System.out.println("The same instance!");
            System.out.printf("%s == %s%n",
                    SingleObject.getInstance(),
                    SingleObject.getInstance());
        } else {
            System.out.println("It's not a Singleton!");
        }
    }
}

The above code produces the following output:

Instantiating SingleObject...
The same instance!
SingleObject@63947c6b == SingleObject@63947c6b

References:

Share with the World!