3

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
NoNaMe
  • 6,020
  • 30
  • 82
  • 110
  • 1
    It depends on the implementation - in case of a broken implementation, chances are that multithread environment causes problems. The pattern itself has nothing to do with it. – Wiktor Zychla Apr 18 '13 at 10:58

4 Answers4

3

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

technophebe
  • 494
  • 3
  • 13
2

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 .

Community
  • 1
  • 1
dShringi
  • 1,497
  • 2
  • 22
  • 36
0

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.

IndoKnight
  • 1,846
  • 1
  • 21
  • 29
-1

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.

nikodz
  • 727
  • 5
  • 13