NoNaMe
NoNaMe

Reputation: 6222

Need some clarification about singleton pattern

Does singleton design pattern make sure one single object reference or there is any chance/possibility of more then one ref of an object while implementing singleton pattern, I think in the case of multi threading there is a some chance of more then one object even we have implemented singleton pattern.

Please help.

Upvotes: 3

Views: 109

Answers (4)

dShringi
dShringi

Reputation: 1497

A singleton pattern is a design pattern that restricts the instantiation of a class to one object. If an instance already exists, it simply returns a reference to that object. However in a multithreaded environment it is possible that 2 separate threads may enter getInstance() simultaneously, check that instance is null and then create 2 instances of the class. Hence in order to prevent it you need to mark your getInstance() as synchronized as in:

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

Check out this post for a better understanding .

Upvotes: 2

technophebe
technophebe

Reputation: 494

It is possible for threading to cause problems with a singleton. You can find a comprehensive set of solutions for making singletons thread safe here:

http://csharpindepth.com/Articles/General/Singleton.aspx

Upvotes: 3

nikodz
nikodz

Reputation: 727

When you have singleton class, you can't create more then one object of that class. You may create many reference on that object, but object will be same.

Upvotes: -1

IndoKnight
IndoKnight

Reputation: 1864

Singleton pattern ensures a single object is created in an application running on a JVM. This holds true even in Multithreaded environment. If not, that's not Singleton or at least badly programmed Singleton.

Upvotes: 0

Related Questions