Are there any issues in multithreaded environment with Singleton pattern?

I have implemented the Singleton class as below:

public class Singleton {

    private static  Singleton instance = null;


    private Singleton() { 
    }

private synchronized static void createInstance() {
    instance = new Singletone();
}


    public static Singleton getInstance() {
        if(instance == null){
            createInstance();
        }
        return instance;
    }

}

But I want to know if it is a correct implementation of a singleton. Are there any problem in multithreaded environment.

Answers


Your implementation is almost correct. The problem is that it is not thread-safe. 2 separate threads may enter getInstance() simultaneously, check that instance is null and then create 2 instances of your class. Here is the fix:

public static synchronized Singletone getInstance() {
    if(instance == null){
        createInstance();
    }
    return instance;
} 

Please pay attention on word synchronized.


public enum Singleton {
    INSTANCE;
    private int val;

    public int getVal() {
        return val;
    }
}

Usage:

Singleton.INSTANCE.getVal();

This is the perfect singleton for Java versions > 5.0 where you have enum support.

Also mentioned in Joshua Bloch's Effective Java. A blog post about it here: Enum Singleton

Update: Also, please use singletons only when you are 100% sure you need one! It kills testability of the code! But you cannot avoid it in places, say in a Factory. But please do not abuse it, use it where ever you actually need it. Understand its use.


Need Your Help

Undefined symbols for architecture armv7 when adding CocoaAsyncSocket

objective-c ios ios5 xmpp xmppframework

I am trying to use XMPPFramework with an iOS5 project (ARC) under xcode 4.2.1 but I am facing this problem. Once I add CocoaAsyncSocket to my project as part of preparing my project to use XMPPFram...

Where do I find an icon of a mouse pointer?

wpf icons

I want my WPF application to have a ToggleButton that contains an image of the mouse pointer in it. The idea is that the user will choose one of three different cursors (the normal mouse cursor, the

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.