File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Why and when Singleton instance of a class is needed? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why and when Singleton instance of a class is needed?" Watch "Why and when Singleton instance of a class is needed?" New topic
Author

Why and when Singleton instance of a class is needed?

Kaush Kane
Ranch Hand

Joined: May 22, 2006
Posts: 37
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

Joined: Jan 29, 2003
Posts: 8791
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 ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11230
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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

Joined: Apr 27, 2006
Posts: 62
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


Could try harder
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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.


[My Blog]
All roads lead to JavaRanch
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

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.


Tony Morris
Java Q&A (FAQ, Trivia)
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

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

Joined: May 22, 2006
Posts: 37
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

Joined: Nov 24, 2005
Posts: 14687
    
  16

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

Joined: May 22, 2006
Posts: 37
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

Joined: Nov 24, 2005
Posts: 14687
    
  16

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

Joined: Aug 16, 2005
Posts: 14111
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why and when Singleton instance of a class is needed?