• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why and when Singleton instance of a class is needed?

 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone let me know why and when the Singleton instance of a class is needed?
And how to obtain a Singleton instance of a class?

Thanks in advance.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch!!

Singleton can be used to manage any resource that has only one instance in the system. I usually use them with caches as a single place to store stuff we might want later. This usage can take you to the same bad places as globals in some other language, so some care is needed. Or a singleton might provide a synchronized interface to a piece of hardware or some other serialized resource.

The classical way to get an instance is:

A very similar pattern is sometimes called Only Create One. Rather than force the single instance through the hidden constructor we have a factory that hides creation or just trust the developers to not create new instances. Servlet is one example ... you could do new() on a servlet but it wouldn't be hooked up to the container in any way so you'd just know better.
[ May 22, 2006: Message edited by: Stan James ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
some folks would argue you NEVER need a singleton - or at least, you should never use the singleton pattern. if you write your code to be a singleton, then what happens a few years down the line when you need 2? or 5? better to have a factory that limits the creation to the number you want.

now, as to how you get the instance of it? there should be (or you need to write) a static method that returns a new instnace if none exist, or a reference to the one that does exist.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stan's MySingleton class will work a little better if getInstance() and theInstance are made static. Otherwise you need an instance in order to get an instance, which is problematic. Also there's a nasty infinite loop in the constructor (if you manage to invoke it).

In many cases it's beneficial to write your code to use a factory method like getInstance() - but most of your code should neither know nor care whether it's going to return the same instance, or different instances each time. Or it might return a subtype of the declared return type. Internally it may be a singleton, but that's no one else's business in most cases. That way if you want to change it later, you can. Using a factory method, and more elaborately, the Abstract Factory pattern, can make your code much more flexible and easy to modify later.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stan's MySingleton class will work a little better if getInstance() and theInstance are made static.


Oops! Thanks for good proofing.

The GoF book on Singleton spends almost a page on factories and subclasses. A simple getInstance() method like the one above (correctly made static) could turn into a factory method later with whatever logic is needed to choose a subtype without damaging any clients, but a separate factory would be cleaner if you anticipate changes in the future.

A tangent: One alternative to singleton is a class with all static methods that passes each method call to a privately contained instance of some other class. The contained class doesn't have to be a singleton enforced by code as shown above because the enclosing class only makes one instance. I have a cache that works this way with pluggable implementations ... a vanilla HashMap cache, one instrumented for usage statistics, one that has an expiry timer. (Hmmm, maybe those should have been decorators!)
 
Ramen Chatterjee
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

I have always thought that an example of a Singleton class is the java.lang.Math class, in so far as it makes no sense to have instances, as the function performed is the same everywhere and there is no state. Is this correct?

Ramen
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ramen Chatterjee:
Hi all

I have always thought that an example of a Singleton class is the java.lang.Math class, in so far as it makes no sense to have instances, as the function performed is the same everywhere and there is no state. Is this correct?

Ramen

No java.lang.Math is not a singleton. java.lang.Math has a private constructor so that it can never be instantiated externally. It is never instantiated internally either, therefore no instances are ever created.
[ May 23, 2006: Message edited by: Garrett Rowe ]
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Fred about the fact that you should not use Singletons. Or at least you have to be prepared for it. Singletons are calling for troubles. One day an application will crash, you'll spend hours debugging, and finally realize that an object is modifying the singleton, while another object was not expecting that. It's a matter of taste.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

some folks would argue you NEVER need a singleton - or at least, you should never use the singleton pattern.

Others will argue that no such thing exists.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://en.wikipedia.org/wiki/Singleton_pattern
It is also considered an anti-pattern since it is often used as a politically correct term for global variable, and hence frowned upon.

As Tony said, some may be ok with it. And some may not.
 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No java.lang.Math is not a singleton. java.lang.Math has a private constructor so that it can never be instantiated externally. It is never instantiated internally either, therefore no instances are ever created.


Why should java.lang.Math should have constructor at all. The methods in java.lang.Math are all static (not instance methods) hence we would never need any instance of java.lang.Math to use its methods. For example we would use Math.ceil(i));. In the example we do not need any instance of java.lang.Math to use the method ceil.
Please correct me if I have any misinterpretations...
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why should java.lang.Math should have constructor at all

Setting a private constructor forces us to use the Math class a static way.
Calling "Math.ceil(i)", and not "new Math().ceil(i)".
 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Setting a private constructor forces us to use the Math class a static way


Constructor is needed to construct a new object of a class. This is my basic understanding of a constructor. In Math class all the methods are static and hence we would never generate any instance of Math class to use any of its methods. If this is the case then why constructor is at all needed??
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry, I probably don't understand your point.
If you don't set the default constructor in private, a default constructor will then be automatically created, so an creating a new instance would be possible. We don't want to create a new instance a Math.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15441
41
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kaush Kane:
Constructor is needed to construct a new object of a class. This is my basic understanding of a constructor. In Math class all the methods are static and hence we would never generate any instance of Math class to use any of its methods. If this is the case then why constructor is at all needed??


First, you have to understand this: if you do not specify a constructor in your class at all, the Java compiler will automatically generate a public, no-args constructor.

A common technique to prevent users from creating an instance of a class is by adding a private constructor to the class. That constructor can't be called from outside the class, so users can't create an instance of the class.

The reason why java.lang.Math has a private constructor is to prevent users from creating instances of the class. The class has only static methods, so you should never have to create an instance of the class - and the private constructor makes sure that you can't.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

First, you have to understand this: if you do not specify a constructor in your class at all, the Java compiler will automatically generate a public, no-args constructor.

It may not necessarily be public. JLS 8.8.7 2e off the top of my head - may have moved for 3e.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic