aspose file tools*
The moose likes Java in General and the fly likes When is it appropriate to use a singleton pattern? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "When is it appropriate to use a singleton pattern?" Watch "When is it appropriate to use a singleton pattern?" New topic
Author

When is it appropriate to use a singleton pattern?

Bob Graffagnino
Ranch Hand

Joined: May 30, 2001
Posts: 81
When is it appropriate to use a singleton pattern? How about with an actionHandler? What if the app is multi threaded?
Rex Rock
Ranch Hand

Joined: Jun 25, 2001
Posts: 82
I don't know the answers to all your questions..but I can tell you when it is appropriate to use singleton.
A singleton is used when you know you need exactly one instance of the class and that it doesnt make sense to have too many objects of the same class. Examples i can think of are the 'system administrator login'..you dont need more than one for that.
In case of multithreaded applications..you probably will make ur function synchronized..to avoid data corruption.
correct me if am wrong..

Originally posted by Bob Graffagnino:
When is it appropriate to use a singleton pattern? How about with an actionHandler? What if the app is multi threaded?

Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
In order to implement a singleton pattern, the constructor of the class is usually made private and if you want to create an instance you must go through a method that CAN get at the constructor. The method then has a chance to keep count of instances out there, and only do the instantiation if the current count is 0. No matter how many threads that you have going, they all get channelled through the one method.


"JavaRanch, where the deer and the Certified play" - David O'Meara
pascal betz
Ranch Hand

Joined: Jun 19, 2001
Posts: 547
hi,
the getInstance() method (a common way to name the method that returns an Instance of this class) should be synchronized to be 100% sure you only have one instance.
Also you can use the Sigelton structure to control the amount (more than one) of instances you create of an Object.
pascal
Joshua Bloch
Author and "Sun God"
Ranch Hand

Joined: May 30, 2001
Posts: 124
Originally posted by Bob Graffagnino:
When is it appropriate to use a singleton pattern? How about with an actionHandler? What if the app is multi threaded?

My book has this to say (Item 2: Enforce the singleton property with a private constructor):
"A singleton is simply a class that is instantiated exactly once [Gamma98, p. 127]. Singletons typically represent some system component that is intrinsically unique, such as a video display or file system."
One thing that my book does not cover is when a singleton is preferred over a non-instantiable utility class, consisting solely of static methods (Item 3). The rule here is simple: use the singleton class if there's a type (typically an interface) containing methods that you want your singleton to implement, if you think there's a good chance that there might be such a type in the future, or if the singleton simply feels like an object.
I'll address the multithreading aspect in my next post. (I don't know what an actionHandler is.)
Regards,

------------------
Joshua Bloch
Author of Effective Java


Joshua Bloch <br />Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0201310058/ref=ase_electricporkchop" target="_blank" rel="nofollow">Effective Java</a> and coauthor of <a href="http://www.amazon.com/exec/obidos/ASIN/032133678X/ref=ase_electricporkchop" target="_blank" rel="nofollow">Java Puzzlers</a>
Joshua Bloch
Author and "Sun God"
Ranch Hand

Joined: May 30, 2001
Posts: 124
Originally posted by Cindy Glass:
In order to implement a singleton pattern, the constructor of the class is usually made private and if you want to create an instance you must go through a method that CAN get at the constructor. The method then has a chance to keep count of instances out there, and only do the instantiation if the current count is 0. No matter how many threads that you have going, they all get channelled through the one method.

Cindy is talking about one particular kind of singleton here: a "lazy singleton", which is created the first time it's used. While this may well be the most common form of singleton, it shouldn't be. It violates Item 37 (Optimize judiciously). The lazy creation is an optimization that is usually unnecessary and can get you into trouble if you're not careful. Here's the straightforward way to implement a singleton, which creates the instance at class-initialization time. (It's copied from Item 2, Enforce the singleton property with a private constructor.):
<pre>
//Singleton with final field
public class Elvis {
public static final Elvis INSTANCE = new Elvis();
private Elvis(){
...
}
...//Remainder omitted
}
</pre>
Alternatively, you can provide a static factory:
<pre>
//Singleton with static factory
public class Elvis {
private static final Elvis INSTANCE =new Elvis();
private Elvis(){
...
}
public static Elvis getInstance(){
return INSTANCE;
}
...//Remainder omitted
}
</pre>
One thing to beware of is serialization. If you want your singleton to implement Serializable, you must provide a readResolve method:
<pre>
// readResolve method to preserve singleton property
private Object readResolve()throws ObjectStreamException {
/*
* Return the one true Elvis and let the garbage collector
* take care of the Elvis impersonator.
*/
return INSTANCE;
}
</pre>
This prevents duplicate instances from existing after deserialization. It's discussed at length in Item 57 (Provide a readResolve method when necessary).
If you really do want to do lazy initialization of the singleton, there are a number of approaches with different performance properties, discussed in Item 48 (Synchronize access to shared mutable data).
Regards,

------------------
Joshua Bloch
Author of Effective Java
[This message has been edited by Joshua Bloch (edited July 11, 2001).]
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Originally posted by Joshua Bloch:
"lazy singleton"

LAZY!!! ACKKKKKKKKKKKKKK!!!
What a Great explaination! Thanks.
Rex Rock
Ranch Hand

Joined: Jun 25, 2001
Posts: 82
Hi Joshua,
If we make the constructor private, then we cannot extend this class, right? coz the subclass constructor will be calling the baseclass constructor and we will get an access violation error or something to that degree. Instead wouldn't it be a better idea to make the constructors protected/package specific which will give us an opportunity to extend this class.
I understand that if we make the constructor protected/package specific, other classes in the same package will be able to create objects..because the constructor is visible, so in such a case would it better to place the singleton class in a separate package???
Rex
Bob Graffagnino
Ranch Hand

Joined: May 30, 2001
Posts: 81
A little background about me, I have 2 years experience developing software. I'm maintaining a client server app and am looking for ways to optimize the code. An "actionHandler" handles actions (events) received from the client. It doesn't have data members. The action handler might do things like saveInvoice() which would make a database call with the data received from the client. Our app has multiple threads so I thought that perhaps this would be a good canidate for a singleton pattern instead of each thread creating its own actionHandler. What if 2 threads call saveInvoice() at the exact same time? Assume saveInvoice() takes care of transaction handling.
Also, when using a singleton pattern, how long will that object live before it is garbage collected?
[This message has been edited by Bob Graffagnino (edited July 11, 2001).]
Joshua Bloch
Author and "Sun God"
Ranch Hand

Joined: May 30, 2001
Posts: 124
Originally posted by Rex Rock:
Hi Joshua,
If we make the constructor private, then we cannot extend this class, right?

Yep, but if you can extend it, it's not a singleton! You can create arbitrarily many instances of the subclass. A similar principle applies to immutable classes. They must not be extendable, or an attacker could make a mutable subclass. (That's why String is final.)
As a more general comment, it is not the case that most classes you right should be extendable. It's fairly difficult to right a class that can be safely extended by someone who is not intimately familiar with its internals, and it's often unnecessary. That's why I say "Design and document for inheritance or else prohibit it" (Item 15).

------------------
Joshua Bloch
Author of Effective Java
Joshua Bloch
Author and "Sun God"
Ranch Hand

Joined: May 30, 2001
Posts: 124
Originally posted by Bob Graffagnino:
A little background about me, I have 2 years experience developing software. I'm maintaining a client server app and am looking for ways to optimize the code. An "actionHandler" handles actions (events) received from the client. It doesn't have data members. The action handler might do things like saveInvoice() which would make a database call with the data received from the client. Our app has multiple threads so I thought that perhaps this would be a good canidate for a singleton pattern instead of each thread creating its own actionHandler. What if 2 threads call saveInvoice() at the exact same time? Assume saveInvoice() takes care of transaction handling.

Aha! I see what you mean. This is not what I'd call a singleton; this is what I'd call a thread-local variable. Java has a class called ThreadLocal (written by yours truly) that provides exactly this abstraction.

Also, when using a singleton pattern, how long will that object live before it is garbage collected?

A true singleton can never be garbage collected so long as its class-loader is reachable. This is essential to guarantee that reasonable semantics. At one time there was a bug wherein the VM eagerly unloaded classes when no instances were reachable. This is no longer the case.
A thread-local, on the other hand, can be garbage collected when the thread whose instance it was goes away. It can also be garbage collected when ThreadLocal instance is no longer reachable. There is a performance issue in the 1.3 release that ThreadLocals aren't gc'd when they're no longer reachable, but this is getting fixed in 1.4. The 1.4 implementation of ThreadLocal will also be much faster, thanks to Doug Lea.

------------------
Joshua Bloch
Author of Effective Java
 
 
subject: When is it appropriate to use a singleton pattern?