Javenue logo


Программирование на Java

Информационные технологии

Singleton Design Pattern in Java

[Вариант статьи на русском языке - здесь.]

Design patterns are descriptions of problems and possible ways of their solving during object-oriented design - OOD.

Maybe the most popular design pattern is Singleton Pattern. It is used to guarantee that there will be only one instance of particular object in the application. The implementation of this pattern can be useful while creating Connection Pool, Factory, Configuration Manager, etc.

In this article you will find basic description of this pattern, several ways to implement it, and the example of its practical usage in Java.

So, the plan for today:

Simple way to define Singleton

One of the simplest ways to implement the Singleton:

public class Singleton {
    private static Singleton _instance = null;

    private Singleton() {}

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

The constructor of this class has to be declared as private. This modificator with the help of getInstance method prevents user from creating several instances of class. So, we can add the final modificator to the class declaration.

As mentioned above, getInstance() method will create the only one instance of Singleton class. Note, this method is synchronized one! This limitation is used to guarantee that in multi-threaded environment there would be only one instance of Singleton class as well as in the single-threaded application.

We can get rid of synchronized keyword. In order to do that the _instance field must be initialized like this:

private static Singleton _instance = new Singleton(),

In that case "if" condition can be removed.

Note that lazy initialization is much more useful when instantiation takes a lot of time. Also, there is a chance to handle exceptions occurred in constructor.

Double-checked locking

The only problem with lazy init - we need it only once. To get rid of it use double-checked locking in such a way:

public final class Singleton {
    private static volatile Singleton _instance = null;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (_instance == null)
            synchronized (Singleton.class) {
                if (_instance == null)
                    _instance = new Singleton();
        return _instance;

By the way, this code was broken until Java SE 1.5. If you are interested, please, read this post.

Instance Holder Singleton

Another notable way to implement Singleton design pattern with lazy initialization:

public final class Singleton {
    private Singleton() {}

    private static class Holder {
        private static final Singleton _instance = new Singleton();

    public static Singleton getInstance() {
        return Holder._instance;

So we moved the synchronization issues to the class loader level.

Still there could be problems when using several Class Loaders or even several JVMs in distributed applications. But it's another story...

And the super modern way of Singleton creation:

    public enum Singleton {

Practical example

I use implemetation of this pattern while working with project configuration. For example, the configuration file "props.txt" consists of properties set.

Consider the following code:

import java.util.*;
import java.io.*;

public class Configuration {
    private static Configuration _instance = null;

    private Properties props = null;

    private Configuration() {
         props = new Properties();
    	try {
	    FileInputStream fis = new FileInputStream(new File("props.txt"));
    	catch (Exception e) {
    	    // catch Configuration Exception right here

    public synchronized static Configuration getInstance() {
        if (_instance == null)
            _instance = new Configuration();
        return _instance;

    // get property value by name
    public String getProperty(String key) {
        String value = null;
        if (props.containsKey(key))
            value = (String) props.get(key);
        else {
            // the property is absent
        return value;

Use the following code to get the value for the specified property:

String propValue = Configuration.getInstance().getProperty(propKey).

Also you can provide some useful constants for your properties:

public static final String PROP_KEY = "propKey",

and get their values in such a way:

String propValue = Configuration.getInstance()

That's all. Comments and questions are appreciated.

Комментариев: 0


  * для публикации комментариев нужно