Chapter 5. The Singleton Pattern: One of a Kind Objects

image with no caption

Our next stop is the Singleton Pattern, our ticket to creating one-of-a-kind objects for which there is only one instance. You might be happy to know that of all patterns, the Singleton is the simplest in terms of its class diagram; in fact, the diagram holds just a single class! But don’t get too comfortable; despite its simplicity from a class design perspective, we are going to encounter quite a few bumps and potholes in its implementation. So buckle up.

image with no caption

Developer: What use is that?

Guru: There are many objects we only need one of: thread pools, caches, dialog boxes, objects that handle preferences and registry settings, objects used for logging, and objects that act as device drivers to devices like printers and graphics cards. In fact, for many of these types of objects, if we were to instantiate more than one we’d run into all sorts of problems like incorrect program behavior, overuse of resources, or inconsistent results.

Developer: Okay, so maybe there are classes that should only be instantiated once, but do I need a whole chapter for this? Can’t I just do this by convention or by global variables? You know, like in Java, I could do it with a static variable.

Guru: In many ways, the Singleton Pattern is a convention for ensuring one and only one object is instantiated for a given class. If you’ve got a better one, the world would like to hear about it; but remember, like all patterns, the Singleton Pattern is a time-tested method for ensuring only one object gets created. The Singleton Pattern also gives us a global point of access, just like a global variable, but without the downsides.

Developer: What downsides?

Guru: Well, here’s one example: if you assign an object to a global variable, then that object might be created when your application begins. Right? What if this object is resource intensive and your application never ends up using it? As you will see, with the Singleton Pattern, we can create our objects only when they are needed.

Developer: This still doesn’t seem like it should be so difficult.

Guru: If you’ve got a good handle on static class variables and methods as well as access modifiers, it’s not. But, in either case, it is interesting to see how a Singleton works, and, as simple as it sounds, Singleton code is hard to get right. Just ask yourself: how do I prevent more than one object from being instantiated? It’s not so obvious, is it?

The Little Singleton

A small Socratic exercise in the style of The Little Lisper

How would you create a single object?

new MyObject();

And, what if another object wanted to create a MyObject? Could it call new on MyObject again?

Yes, of course.

So as long as we have a class, can we always instantiate it one or more times?

Yes. Well, only if it’s a public class.

And if not?

Well, if it’s not a public class, only classes in the same package can instantiate it. But they can still instantiate it more than once.

Hmm, interesting.

Did you know you could do this?

No, I’d never thought of it, but I guess it makes sense because it is a legal definition.

What does it mean?

I suppose it is a class that can’t be instantiated because it has a private constructor.

Well, is there ANY object that could use the private constructor?

Hmm, I think the code in MyClass is the only code that could call it. But that doesn’t make much sense.

Why not?

Because I’d have to have an instance of the class to call it, but I can’t have an instance because no other class can instantiate it. It’s a chicken-and-egg problem: I can use the constructor from an object of type MyClass, but I can never instantiate that object because no other object can use “new MyClass()”.

Okay. It was just a thought.

What does this mean?

MyClass is a class with a static method. We can call the static method like this:


Why did you use MyClass, instead of some object name?

Well, getInstance() is a static method; in other words, it is a CLASS method. You need to use the class name to reference a static method.

Very interesting. What if we put things together.

Now can I instantiate a MyClass?

Wow, you sure can.

So, now can you think of a second way to instantiate an object?


Can you finish the code so that only ONE instance of MyClass is ever created?

Yes, I think so...

(You’ll find the code on the next page.)

Dissecting the classic Singleton Pattern implementation

image with no caption

Watch it!

If you’re just flipping through the book, don’t blindly type in this code; you’ll see it has a few issues later in the chapter.

The Chocolate Factory

Everyone knows that all modern chocolate factories have computer-controlled chocolate boilers. The job of the boiler is to take in chocolate and milk, bring them to a boil, and then pass them on to the next phase of making chocolate bars.

Here’s the controller class for Choc-O-Holic, Inc.’s industrial strength Chocolate Boiler. Check out the code; you’ll notice they’ve tried to be very careful to ensure that bad things don’t happen, like draining 500 gallons of unboiled mixture, or filling the boiler when it’s already full, or boiling an empty boiler!

image with no caption
image with no caption

Brain Power

Choc-O-Holic has done a decent job of ensuring bad things don’t happen, don’t ya think? Then again, you probably suspect that if two ChocolateBoiler instances get loose, some very bad things can happen.

How might things go wrong if more than one instance of ChocolateBoiler is created in an application?

Singleton Pattern defined

Now that you’ve got the classic implementation of Singleton in your head, it’s time to sit back, enjoy a bar of chocolate, and check out the finer points of the Singleton Pattern.

Let’s start with the concise definition of the pattern:


The Singleton Pattern ensures a class has only one instance, and provides a global point of access to it.

No big surprises there. But let’s break it down a bit more:

  • What’s really going on here? We’re taking a class and letting it manage a single instance of itself. We’re also preventing any other class from creating a new instance on its own. To get an instance, you’ve got to go through the class itself.

  • We’re also providing a global access point to the instance: whenever you need an instance, just query the class and it will hand you back the single instance. As you’ve seen, we can implement this so that the Singleton is created in a lazy manner, which is especially important for resource-intensive objects.

Okay, let’s check out the class diagram:

image with no caption

Houston, Hershey, PA we have a problem...

It looks like the Chocolate Boiler has let us down; despite the fact we improved the code using Classic Singleton, somehow the ChocolateBoiler’s fill() method was able to start filling the boiler even though a batch of milk and chocolate was already boiling! That’s 500 gallons of spilled milk (and chocolate)! What happened!?

image with no caption

Could the addition of threads have caused this? Isn’t it the case that once we’ve set the uniqueInstance variable to the sole instance of ChocolateBoiler, all calls to getInstance() should return the same instance? Right?

image with no caption

Dealing with multithreading

Our multithreading woes are almost trivially fixed by making getInstance() a synchronized method:

image with no caption

Good point, and it’s actually a little worse than you make out: the only time synchronization is relevant is the first time through this method. In other words, once we’ve set the uniqueInstance variable to an instance of Singleton, we have no further need to synchronize this method. After the first time through, synchronization is totally unneeded overhead!

image with no caption

Can we improve multithreading?

For most Java applications, we obviously need to ensure that the Singleton works in the presence of multiple threads. But, it is expensive to synchronize the getInstance() method, so what do we do?

Well, we have a few options...

1. Do nothing if the performance of getInstance() isn’t critical to your application.

That’s right; if calling the getInstance() method isn’t causing substantial overhead for your application, forget about it. Synchronizing getInstance() is straightforward and effective. Just keep in mind that synchronizing a method can decrease performance by a factor of 100, so if a high-traffic part of your code begins using getInstance(), you may have to reconsider.

2. Move to an eagerly created instance rather than a lazily created one.

If your application always creates and uses an instance of the Singleton or the overhead of creation and runtime aspects of the Singleton are not onerous, you may want to create your Singleton eagerly, like this:

image with no caption

Using this approach, we rely on the JVM to create the unique instance of the Singleton when the class is loaded. The JVM guarantees that the instance will be created before any thread accesses the static uniqueInstance variable.

3. Use “double-checked locking” to reduce the use of synchronization in getInstance().

With double-checked locking, we first check to see if an instance is created, and if not, THEN we synchronize. This way, we only synchronize the first time through, just what we want.

Let’s check out the code:

image with no caption

If performance is an issue in your use of the getInstance() method then this method of implementing the Singleton can drastically reduce the overhead.

Watch it!

Double-checked locking doesn’t work in Java 1.4 or earlier!

Unfortunately, in Java version 1.4 and earlier, many JVMs contain implementations of the volatile keyword that allow improper synchronization for double-checked locking. If you must use a JVM earlier than Java 5, consider other methods of implementing your Singleton.

Meanwhile, back at the Chocolate Factory...

While we’ve been off diagnosing the multithreading problems, the chocolate boiler has been cleaned up and is ready to go. But first, we have to fix the multithreading problems. We have a few solutions at hand, each with different tradeoffs, so which solution are we going to employ?

image with no caption


At this point, the Chocolate Factory is a happy customer and Choc-O-Holic was glad to have some expertise applied to their boiler code. No matter which multithreading solution you applied, the boiler should be in good shape with no more mishaps. Congratulations. You’ve not only managed to escape 500lbs of hot chocolate in this chapter, but you’ve been through all the potential problems of the Singleton.


Rumors of Singletons being eaten by the garbage collectors are greatly exaggerated

Prior to Java 1.2, a bug in the garbage collector allowed Singletons to be prematurely collected if there was no global reference to them. In other words, you could create a Singleton and if the only reference to the Singleton was in the Singleton itself, it would be collected and destroyed by the garbage collector. This leads to confusing bugs because after the Singleton is “collected,” the next call to getInstance() produces a shiny new Singleton. In many applications, this can cause confusing behavior as state is mysteriously reset to initial values or things like network connections are reset.

Since Java 1.2 this bug has been fixed and a global reference is no longer required. If you are, for some reason, still using a pre-Java 1.2 JVM, then be aware of this issue; otherwise, you can sleep well knowing your Singletons won’t be prematurely collected.

Tools for your Design Toolbox

You’ve now added another pattern to your toolbox. Singleton gives you another method of creating objects—in this case, unique objects.

image with no caption


As you’ve seen, despite its apparent simplicity, there are a lot of details involved in the Singleton’s implementation. After reading this chapter, though, you are ready to go out and use Singleton in the wild.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.