aspose file tools*
The moose likes Java in General and the fly likes Singletons -  What are they and how/why would you use them? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Singletons -  What are they and how/why would you use them?" Watch "Singletons -  What are they and how/why would you use them?" New topic
Author

Singletons - What are they and how/why would you use them?

Sam Smoot
Ranch Hand

Joined: Apr 18, 2002
Posts: 238
I've been told to create a Singlton object for my current projcet to store in memory as a menu object for all users.
My only response is ?? Huh ??
Thanks.
p.s. This isn't homework... Homework is easier and usually makes sense...


CNSS/NSA Infosec Professional,<br />Software Engineer
Juanjo Bazan
Ranch Hand

Joined: Feb 04, 2002
Posts: 231
A Singleton class is simply a class for which only a single instance can be created.
You enforce this using a private constructor.
The instance is retrieved through a static method that checks if there is already an instance created returnint it if so and returning a new one if not.
So you can create asingleton class just with this code:

HTH
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

Let's say you have a graphic screen (or menu list) that you know will be used in lots of contexts, possibly even by multiple users. At the same time, the state of the object only needs to be maintained in one copy. A singleton helps enforce a "one-copy-only" rule so that this thing isn't constructed every time it's need, but maintains the semantics of being constructed for convenience.
The user asks for the object by way of calling the constructor; a singleton makes the object if it doesn't already exist. Otherwise, the constructor call returns as expected. Either way, the user is assured it has the resource it needs.


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Sam Smoot
Ranch Hand

Joined: Apr 18, 2002
Posts: 238
J.B.
In reference to the code you posted (to make sure I understand it), the commentted area "Do whatever you need" could actually execute the menu building fuction (or call the class to do such) while the second (bottom) section executes the constructor only if the singleton instance doesn't exist. Do I need to pass anything in the parameter list, or is that only dependant on the method called (as with any other java class / method)? :roll: What keeps the garbage collector from collecting this once it has finished executing?
I'm trying to understand this, but it just keeps getting deeper and deeper... I think I need a bigger shovel or at least a very long snorkel...
Thanks.
Juanjo Bazan
Ranch Hand

Joined: Feb 04, 2002
Posts: 231
Originally posted by Sam Smoot:
In reference to the code you posted (to make sure I understand it), the commentted area "Do whatever you need" could actually execute the menu building fuction (or call the class to do such)while the second (bottom) section executes the constructor only if the singleton instance doesn't exist.

Thats right.

Do I need to pass anything in the parameter list, or is that only dependant on the method called (as with any other java class / method)?

The code I posted is just a "skeleton". You can set the parameter list of the getInstance() method according to your needs. If you need to pass some params to the constructor, you should pass that params to the getInstance() method in order it can pass them to the constructor if necessary.
And of course you can also add as methods as you need, that could be called from any class using MySingleton.getInstance().method();

What keeps the garbage collector from collecting this once it has finished executing?

Nothing. With the Singleton Pattern, what you get is that it doesn't matter how many users or classes are trying to use that class at the same time:All of them will be accessing the same object, it won't be created many times, just once((this is an advantage for memory management and fwill ease the garbage collecting).
But if nobody is using the object and it is garbaged collected, the next user trying to use it will cause a new instance(again the first) to be created it again...

I'm trying to understand this, but it just keeps getting deeper and deeper... I think I need a bigger shovel or at least a very long snorkel...
Thanks.

Don't worry, if you use this pattern, sooner or latter you will understand it clearly .Then will be the time to learn about the Singleton Factory and how to subclass a Singleton...

HTH
Sayed Ibrahim Hashimi
Ranch Hand

Joined: May 17, 2001
Posts: 148
But if nobody is using the object and it is garbaged collected, the next user trying to use it will cause a new instance(again the first) to be created it again...

Once its created how will it get garbage collected? You have a static reference(theInstance) to it in your MySingleton class.
Besides the fact that someone can assign it null.


SCJP 1.4<br /><a href="http://www.cise.ufl.edu/~sih" target="_blank" rel="nofollow">www.cise.ufl.edu/~sih</a>
Philip Shanks
Ranch Hand

Joined: Oct 15, 2002
Posts: 189
Your application has to maintain a valid reference to the object. Usually, this is done in the Singleton's class. When a client needs access to the object, they get a copy of the reference. If you don't want the Singleton to continue its existence until the program exits, then you may want to build in some timeout or other expiration/invalidation behavior. This too would go into the Singleton class to be managed internally.
See pages 34-7 of Applied Java Patterns, Stelting and Maassen, 2002 for a thorough coverage.
This is a good general patterns reference for Java coders, in that it is essentially a Java port of the GoF book.
PCS
[ November 27, 2002: Message edited by: Philip Shanks ]

Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
Drake Silver
Ranch Hand

Joined: Apr 21, 2002
Posts: 80
Originally posted by Sam Smoot:
I've been told to create a Singlton object for my current projcet to store in memory as a menu object for all users.
My only response is ?? Huh ??
Thanks.
p.s. This isn't homework... Homework is easier and usually makes sense...

read this:
http://www-106.ibm.com/developerworks/java/library/j-dcl.html?dwzone=java


"Shh, Zog....here come one Now!"
Sam Smoot
Ranch Hand

Joined: Apr 18, 2002
Posts: 238
O.k. I'm back from vacation and just as confused as ever... Maby I can use the leftover turkey to kick the gray matter in gear.
I appreciate the responses, maby this will make sense this week. Of course, if not,
{menacing music starts...}
I'll be Back...
{crescendo; background screams...}
Wilfried LAURENT
Ranch Hand

Joined: Jul 13, 2001
Posts: 269
You can also see some threads on singletion in the UML forum.
W.
Brian McCallister
Greenhorn

Joined: Dec 03, 2002
Posts: 19
Rules for using singleton's:
1) Don't use them.
2) For experts only, don't use them unless you cannot find another way.
The reason for this is that Singlton's usually wind up just being global variables. There are places they are appropriate, but those generally have to be for things unrelated to the main logic of a class or method - logging for instance.
If the use of the Singleton is important for the core logic of something, and it has to be a Singleton as opposed to static method calls, then reconsider your use. You only need a Singleton over static methods if it is holding state, and that state can be changed. Now, if the state can be changed and it is accessible anywhere... you have global data and all the pitfalls therein.
-Brian
Christopher Farnham
Greenhorn

Joined: Sep 18, 2002
Posts: 12
This may be a matter of opinion, but I disagree with your assertion that Singletons should be avoided unless you're an expert. I'm posting this because I don't want Sam Smoot to be confused.
The Singleton is often a programmer's first introduction to design patterns and I think that Sam is on the verge of stepping into a larger world in respect to his programming skills.
I use Singletons fairly often for components that I don't want multiple instances of. I recently wrote one for a class which creates a collection of objects based on an XML file. I have multiple objects accessing this collection, and I don't want the XML parsed each time the collection is accessed.
If a Singleton is accessed within the proper scope. Garbage collection can recycle them and they aren't memory hogs.
Everything has its use and place... and I often find Singletons useful.


Christopher Farnham<br />Boston, MA<p>"Perfect is the Enemy of Good"
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Singletons - What are they and how/why would you use them?