28
February
2006

Singleton Design Pattern in Java

Posted in: Java technologies (translated), Паттерны проектирования |

The Russian version of this article can be found here.
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 realization 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 and the example of its practical usage (in Java).
Look through the following code:

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. 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(),

Of course, the “if” construction is not critical in this case.

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”));
	    props.load(fis);
    	}
    	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()
    .getProperty(Configuration.PROP_KEY).

That’s all. Comments and corrections are appreciated.

5 Comments »

RSS feed for comments on this post. TrackBack URI



Lenchik
February 5, 2009 #

Real singleton from Joshua Bloch…
public enum Singleton {
INSTANCE;
public void foo() { }
}

Omar
December 1, 2010 #

This Singleton is very useful to avoid load properties file every time you need it, so it saves much resource and is easy to use. Specially for enterprise apps.

Thank you!

April 9, 2011 #

Nice article. just to add
While writing Singleton class you also need to consider following points :
1) Lazy initialization
2) Early initialization
3) Serialization
4) Many ClassLoaders
5) Cloning

Thanks
Javin
Singleton Pattern in Java

sagar
September 29, 2011 #

thank you

April 29, 2012 #

Singleton Pattern in Java a very good code snippet
http://sshadmincontrol.com/java-singleton-design-pattern
I”m using it for years now with no issues

Leave a comment

XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> <pre>