Enterprise Integration Zone is brought to you in partnership with:

Mainak is an experienced Technology Consultant specializing in JEE, Web Development and Open source technologies. He is currently based out of United Kingdom. He is die hard technology enthusiast trying to explore the latest in the world of technology. In past time he loves blogging on his website: http://idiotechie.com. Mainak is a DZone MVB and is not an employee of DZone and has posted 11 posts at DZone. You can read more from them at their website. View Full User Profile

Singleton Design Pattern – An Introspection w/ Best Practices

02.13.2013
| 163015 views |
  • submit to reddit

Sample Code:

Factory.java

public abstract class Factory {
 protected abstract StatementType createStatements(String selection);
 }

StatementFactory.java

public class StatementFactory extends Factory {
    private static StatementFactory uniqueInstance;
 
    private StatementFactory() {
    }
 
    public static StatementFactory getUniqueInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new StatementFactory();
            System.out.println("Creating a new StatementFactory instance");
        }
        return uniqueInstance;
 
    }
 
    public StatementType createStatements(String selection) {
        if (selection.equalsIgnoreCase("detailedStmt")) {
            return new DetailedStatement();
        } else if (selection.equalsIgnoreCase("miniStmt")) {
            return new MiniStatement();
        }
        throw new IllegalArgumentException("Selection doesnot exist");
    }
}

StatementType.java

public interface StatementType {
    String print();
}

DetailedStatement.java

public class DetailedStatement implements StatementType {
    @Override
    public String print() {
        System.out.println("Detailed Statement Created");
        return "detailedStmt";
    }
}

MiniStatement.java

public class MiniStatement implements StatementType {
    @Override
    public String print() {
        System.out.println("Mini Statement Created");
        return "miniStmt";
    }
}

Client.java

public class Client {
 
    public static void main(String[] args) {
        System.out.println("Enter your selection:");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String selection = null;
        try {
            selection = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Factory factory = StatementFactory.getUniqueInstance();
        StatementType objStmtType = factory.createStatements(selection);
        System.out.println(objStmtType.print());
    }
 
}

Conclusion:

In the above articles we have gone into the details of the Singleton pattern, how to implement singleton pattern along with a practical application. Though singleton pattern looks a simple implementation we should resist ourselves from using it until and unless there is a strong requirement for it. You can blame the unpredictable nature of the results in the multi-threading environment. Though we can use enum in Java 5 and above it sometimes get difficult to implement your logic always in enum or there might be legacy code before Java 5. Hope our readers have liked this article.

Published at DZone with permission of Mainak Goswami, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Niklas Efternamn replied on Wed, 2013/02/13 - 8:42am

Your following statement is incorrect: "In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine", when using static menbers. It is only true per Class Loader, not JVM.

Stoo Mcstooo replied on Wed, 2013/02/13 - 10:05am

Double checked locking doesn't work well in java. See Java Concurrency in Practice, page 349 which recommends against it. At minimum the singleton should be volatile to work, and even then the performance improvement is negligible.

Dapeng Liu replied on Wed, 2013/02/13 - 12:03pm

singletons should really be managed by DI containers


Mainak Goswami replied on Wed, 2013/02/13 - 2:43pm in response to: Niklas Efternamn

Thanks Niklas. You are correct. Static deals with per class basis so when using static members it will be per class loader basis. However imagine the situation where there is only one application in the JVM which is used by this class loader. So implicitly singleton will have a unique instance throughout the JVM...isn't it? Please let me know your thoughts.

Mainak Goswami replied on Wed, 2013/02/13 - 2:44pm in response to: Stoo Mcstooo

Thanks Stoo. Perhaps this is the reason why I have mentioned that enum will be a most preferred option.

Gauthier Jacques replied on Thu, 2013/02/21 - 10:16am

Singleton is an anti-pattern and should never be used. Using an IoC container such as Spring instead is much more efficient, easy, secure, modular.

Mainak Goswami replied on Thu, 2013/02/21 - 1:46pm in response to: Gauthier Jacques

HI Gauthier,

Thanks for your reading this article. The point you have made is debatable and controversial. This was, is and will be one of the most debatable topic. 

Anyways enjoy reading.

Oleksandr Alesinskyy replied on Wed, 2013/02/27 - 8:08am

A code example

public static volatile SingletonExample getSingletonInstance()

is incorrect - "volatile" keyword is intended for variables only.

Mainak Goswami replied on Wed, 2013/02/27 - 1:49pm in response to: Oleksandr Alesinskyy

Agree. That was a typo.

Miguel Reboiro-jato replied on Thu, 2013/02/28 - 4:55am

I think that in Java, in most cases, there is no real advantage on using the "lazy" version instead of the "early" version. In Java, the static fields are not initialized until the class is used for the first time, and in the singleton pattern the class is usually used for the first time when the "getSingleton()" method is invoked. So, the "instance" field will be initialized at the same execution time in both cases. Therefore, I think that the "early" version is better, as the "if" statements are uneeded.

Lokesh Gupta replied on Wed, 2013/03/06 - 6:01am

 A very good article indeed. I also wrote an article covering above techniques and few more here.

http://howtodoinjava.com/2012/10/22/singleton-design-pattern-in-java/


My favorite is bill pugh solution using inner class to maintain singleton.

Michael Nitschke replied on Mon, 2013/03/18 - 11:36am

Singletons are an antipattern. Point! For over six years now.

The only debate that is going on about Singletons around here, is if they are just bad or evil as a goto.

Most of the time you get a better, more elegant solution when you try to avoid it. (As it is usual the case if you are experiencing a code smell)

Cheers Mike

Amit Shukla replied on Tue, 2013/05/07 - 9:17pm

Mainak, Can we break singleton using reflection?

And why is double locking not safe? I think these two points are missing, esp the first one.


Mainak Goswami replied on Fri, 2013/05/10 - 3:53pm

Hi Amit,

Thanks for your query.

To reply to your first question - Yes you can break the singleton using reflection. But there are ways to prevent the reflection attack. I think use of enum can prevent the reflection attack.

answering second question - double checked locking is not safe way of implementing singleton because the jvm have some flexibility of controlling the behavior in a multithreaded environment....specially in java versions 1.4 and before this inconsistency has been found....

Hope this helps.

Thanks

Shekhar Gupta replied on Wed, 2013/05/15 - 7:15am

Hi mainak,

I dont think we can subclass a Singleton class. The reason I see behind that is for private constructor it has. Whenever you extend any single ton class, its constructor would not be visible to it's child. So It can't extend it.

Mainak Goswami replied on Wed, 2013/05/15 - 2:33pm in response to: Shekhar Gupta

Hi Shekhar,

Thanks for your response.  To answer your question I would say that singleton will restrict the instances but it does not restrict inheritance. It may not serve any practical purpose but it is possible to extend a singleton class.

Imagine the situation if you have a anonymous subclass or imagine that you have other methods in the class which are not private - perhaps you can use them. As I said in my article until you use final keyword you can go ahead an subclass it. 

Hope this clarifies.


Shekhar Gupta replied on Sun, 2013/05/19 - 5:31am in response to: Mainak Goswami

Hi Mainak,

I guess I'm pretty sure that you can't inherit any Singleton class because of fact that it does have a private constructor. I shall be delighted if you counter my argument with any example.

Mainak Goswami replied on Sun, 2013/05/19 - 4:57pm in response to: Shekhar Gupta

Hi Shekhar,

You can create an inner class which inherits from the parent Singleton class.

class TestInnerClass extends SingletonExample{   } In the client calling class you can check if the TestInnerClass IS-A SingletonExample relationship using instanceof variable. Hope this helps.

Markus Kolb replied on Fri, 2013/05/24 - 7:13am

 Why there is never ever a reference to this solution...?

http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh 

It is thread-safe without any volatile magic or sync-overhead and it is initialized lazy.

Gauthier Jacques replied on Fri, 2013/05/24 - 7:56am

I totally agree with you. Even though I maintain that singletons are among the worst design mistakes I made when I was a junior, the Bill Pugh solution seems to be the most elegant one.

Oleksandr Alesinskyy replied on Fri, 2013/05/24 - 8:52am in response to: Gauthier Jacques

 The problem is that starting from Java 7 this solution cannot guarantee that singleton is a singleton (for reasons explained here http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.7



Gauthier Jacques replied on Fri, 2013/05/24 - 9:28am in response to: Oleksandr Alesinskyy

 Then back to square 1 : use IoC container and not singletons ! :-)

Markus Kolb replied on Fri, 2013/05/24 - 9:40am in response to: Oleksandr Alesinskyy

 Perhaps you can be more specific?!

Are you talking about class reloading?

The code says:

public static final Singleton INSTANCE = new Singleton();

The final says INSTANCE is INSTANCE and stays INSTANCE, doesn't it?

So reloading should be transparent in this case?!


Manoj Kumar replied on Tue, 2013/07/09 - 3:51am

 What is instance control?

Instance control basically refers to single instance of the class OR singleton design pattern .

Java 1.5 onwards we should always prefer ENUM to create singleton instance. It is absolutely safe . JVM guarantees that. All earlier mechanical of controlling instance to single are already broken.

So in any interview you can confidently say ENUM= provides perfect singleton implementation .

Now what is readResolve?

readResolve is nothing but a method provided in serializable class . This method is invoked when serialized object is deserialized. Through readResolve method you can control how instance will be created at the time of deserialization.Lets try to understand some code

public class President {

private static final President singlePresident = new President();

private President(){

}

}

This class generates single instance of President class. singlePresident is static instance and same will be used across.  

But do you see it breaks anywhere?


Please visit http://efectivejava.blogspot.in/ for more details on this

Dinesh Bansal replied on Sat, 2013/08/10 - 2:09am

design problem is awesome. I was aware of singleton and factory pattern but did not know to apply them. Good article to understand the application of patterns.


Mainak Goswami replied on Sat, 2013/08/10 - 1:32pm

Thanks Dinesh for your feedback. Please keep visiting my space for more articles.

Andrew W replied on Wed, 2013/08/14 - 11:57pm

You only need to use the final keyword. Singletons are in use all over the JRE, files for examples, or have you ever used a filesystem that had two different files with the same path?

final File singleton = new File( "/tmp/test-it" );

 

some of your commenters were pretty rude, and pretty wrong.

How are you going t use this singleton, btw?

 

Dru

 

Srujana Mardi replied on Sun, 2013/09/15 - 8:43am

Hi Mainak,

Thanks for your blog. Sequence of steps which you explained is very easy to understand. with your article I have cleared all of my doubts but having doubt on using "volatile" keyword in double checked logging scenario. could you please let me know what exactly volatile and reason for using volatile in static method getSingletonInstance() method. Thanks for your response.



Henkz Sall replied on Sun, 2014/03/02 - 2:58pm in response to: Niklas Efternamn

willy filmes online shows a flow chart from the book co-authored by Charlie Hunt and Binu John. This chart shows the process of Java application performance tuning.

Henkz Sall replied on Sat, 2014/03/08 - 8:35pm

What youre indicating is utterly correct. I realize which anyone must filmes online

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.