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”));
    	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()

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 corrections are appreciated.


RSS feed for comments on this post. TrackBack URI

February 5, 2009 #

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

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

Singleton Pattern in Java

September 29, 2011 #

thank you

April 29, 2012 #

Singleton Pattern in Java a very good code snippet
I”m using it for years now with no issues

March 24, 2015 #

HI Sir/Madam

Can you outsource some SEO business to us? We will work according to you and your clients and for a long term relationship we can start our SEO services in only $99 per month per website.

Looking forward for your positive reply

Thanks & regards
Ashish Kumar
Email- info@semmiami.com

PS: Humble request we are not spammers. We take hours to research on sites and keywords to contact web-master. If by sending this email we have made an offence to you or to your organization then we extremely apologize for the same. In order to stop receiving such emails from us in future please reply with “Remove or Not Interested” as subject line. Many thanks for having your kind look to our email.
Must Reply.

Leave a comment

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