Can anyone provide an example of a singleton pattern and explain why they are necessary?
-
4To accept answers to your questions, you need to click the check-mark that appears in gray below the score of an answer: this marks will turn green which means you accepted it, see http://stackoverflow.com/faq – Gregory Pakosz Jan 05 '10 at 21:29
6 Answers
Before going the singleton route, reconsider. Do you really need a singleton? If you're asking for scenarios when you need to implement singletons, it's because the need for them didn't really express. You're better off not introducing singletons in your code base just because it feels cool to follow design patterns.
Clean Code Talks - Global State and Singletons
However, what's really worth knowing is Dependency Injection.
Now if you really want to implement singletons in Java, I would recommend Joshua Bloch's "Effective Java" way of implementing them:
public class Singleton
{
public static Singleton getInstance() {
return SingletonHolder.instance;
}
private Singleton() {}
private static final class SingletonHolder {
static final Singleton instance = new Singleton();
}
}
The JLS guarantees the JVM will not initialize instance until someone calls getInstance();
Final note, the Double Checked Locking Pattern is broken in Java up to Java 5. The Java 5 memory model makes the DCL pattern thread safe but it makes it slower than the SingletonHolder
class method while the original intent was performance optimization.
EDIT: As @Luno pointed out, since the second edition of the book, the preferred way is:
As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

- 69,011
- 20
- 139
- 164
-
7Actually, Josh Bloch writes that the best way to implement singleton is to use enum. enum MySingletonClass { INSTANCE; } Because it is thread save, it makes no problems with serialisation, no security risks. – Mirek Pluta Jan 05 '10 at 20:53
-
1Indeed, in the second edition of Effective Java, Joshua Bloch writes that **a single-element enum type is the best way to implement a singleton** (http://www.informit.com/articles/article.aspx?p=1216151&seqNum=3). – Pascal Thivent Jan 05 '10 at 20:56
-
@Luno & @Pacal: yep thx, I googled for an excerpt and edited the answer for completeness – Gregory Pakosz Jan 05 '10 at 20:59
-
Re: Double Checked Locking - the Java 5 memory model has appropriate semantics for `volatile` fields such that it **does** work in version 5 and later runtime environments, so saying it's broken is no longer accurate. Having said that, there's *often* a better way to achieve one's goals than to use DCL anyway... :-) – Andrzej Doyle Jan 07 '10 at 01:46
-
@Andrzej thx for pointing this out, I edited the answer with a reference to https://www.ibm.com/developerworks/library/j-jtp03304/#3.2 – Gregory Pakosz Jan 07 '10 at 08:00
-
a few issues: (1) Hevery basically says in his presentation about dependency injection that "global states are bad" (my interpretation). But how does he explain named constants such as `Math.PI` and functions such as `Math.sin(int)`? How does one use these things without global states? Also, (2) regarding Bloch, using an enum as a singleton might be good for serialization, but you can't extend another class. For example, say I have a class `Wizard` and another class `HarryPotter extends Wizard` which I want to be a singleton? `HarryPotter` can't be an enum because enums can't extend classes. – chharvey Sep 05 '11 at 23:10
Basically, in Java you implement singleton by giving a class a private no-args constructor (private MyClass()
), and statically (or lazily) initializing a single instance of the class which is returned by a static MyClass getInstance()
method.
You would use this when you want there to be no more than a single instance of your class throughout the entire application.

- 80,905
- 18
- 123
- 145
danben has a pretty good summary of what a singleton is, so I won't rehash it.
As far as uses go, singletons are often thinly veiled implementations of global variables (which is a bad idea). They can be useful for things like message routers or manager classes (among other things).

- 5,596
- 8
- 42
- 56
'Simply Singleton' at JavaWorld
And if you really want to get into the trenches, start reading about "static vs singleton" on the groups, or Google it. Always a hot topic to say the least!

- 28,441
- 31
- 139
- 229
One often underappreciated place where singletons are good is when you want to abstract away the existence of state. An example is a random number generator. At the level of the abstraction, it just generates random numbers and doesn't have any state that the caller should need to care about. At the implementation level, though, state is involved. Another is when a function caches results or intermediate computations, but you want to hide this detail from the caller.
There is a significant tradeoff here. If you make things like these singletons, you decrease the amount of implementation details the caller of your function has to care about, thus decreasing coupling in that direction. However, at the same time you strongly couple your function to the singleton object, making it harder to test, etc. The decision about whether to use a singleton should be made based on which direction you care about reducing coupling in more.

- 67,514
- 53
- 213
- 334
assume you have only one printer in office and you need Ensure a printer class has only one instance
printer{
private static printer instance =null;
private printer(){}
public static printer getinst(){
if( instance==null){
instant = new printer();
}
return instance;
}
}
in the main
printer v=printer.geti();