When is a singleton not a singleton?

Avoid multiple singleton instances by keeping these tips in mind

The singleton is a useful design pattern for allowing only one instance of your class, but common mistakes can inadvertently allow more than one instance to be created. In this article, I'll show you how that can happen and how to avoid it.

The singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one singleton instance, any instance fields of a singleton will occur only once per class, just like static fields.

Singletons often control access to resources such as database connections or sockets. For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the singleton makes sure that only one connection is made or that only one thread can access the connection at a time. If you add database connections or use a JDBC driver that allows multithreading, the singleton can be easily adjusted to allow more connections.

Moreover, singletons can be stateful; in this case, their role is to serve as a unique repository of state. If you are implementing a counter that needs to give out sequential and unique numbers (such as the machine that gives out numbers in the deli), the counter needs to be globally unique. The singleton can hold the number and synchronize access; if later you want to hold counters in a database for persistence, you can change the private implementation of the singleton without changing the interface.

On the other hand, singletons can also be stateless, providing utility functions that need no more information than their parameters. In that case, there is no need to instantiate multiple objects that have no reason for their existence, and so a singleton is appropriate.

The singleton should not be seen as way to implement global variables in Java; rather, along the lines of the factory design patterns, the singleton lets you encapsulate and control the creation process by making sure that certain prerequisites are fulfilled or by creating the object lazily on demand.

However, in certain situations, two or more singletons can mysteriously materialize, disrupting the very guarantees that the singleton is meant to provide. For example, if your singleton Frame is meant as a global user interface for your application and two are created, your application will have two Frames on the screen -- quite confusing for the user. Further, if two counters are created where one was intended, then clients requesting numbers will not get the desired sequence 1, 2, 3... but rather a multiple sequence such as 1, 1, 2, 2, 3, 3, 3.... Additionally, if several instances of a database-connection singleton are created, you might start receiving SQLExceptions complaining about "too many database connections."

In this article, I'll describe those phenomena and how to avoid them. After discussing how to implement the singleton, I'll go over the sometimes surprising causes for the phenomena one by one, showing you how they occur and how you can avoid making those mistakes. I hope that in the process you will learn about classloading, multithreading, distributed systems, Design Patterns, and other interesting topics, as I did.

Implementing singletons

There are a few ways to implement singletons. Although you can get singleton-like behavior with static fields and methods [for example, java.lang.Math.sin(double)], you gain more flexibility by creating an instance. With singletons implemented as single instances instead of static class members, you can initialize the singleton lazily, creating it only when it is first used. Likewise, with a singleton implemented as single instance, you leave open the possibility of altering the class to create more instances in the future. With some implementations of the singleton, you allow writers of subclasses to override methods polymorphically, something not possible with static methods.

Most commonly, you implement a singleton in Java by having a single instance of the class as a static field. You can create that instance at class-loading time by assigning a newly created object to the static field in the field declaration, as seen in Listing 1.

Listing 1

public class MySingleton {
    private static  MySingleton _instance =
        new MySingleton();
    private MySingleton() {
        // construct object . . .
    }
    public static MySingleton getInstance() {
        return _instance;
    }
    // Remainder of class definition . . .

Alternatively, you can instantiate it lazily, on first demand, as seen in Listing 2. You keep the constructor private to prevent instantiation by outside callers.

Listing 2

public class MySingleton {
    private static  MySingleton _instance;
    private MySingleton() {
        // construct object . . .
    }
    // For lazy initialization
    public static synchronized MySingleton getInstance() {
        if (_instance==null) {
            _instance = new MySingleton();
        }
        return _instance;
    }
        // Remainder of  class definition . . .
}

Both singleton implementations do not allow convenient subclassing, since getInstance(), being static, cannot be overridden polymorphically. Other implementations prove more flexible. While I don't have the space to describe alternative implementations in detail, here are a couple of possibilities:

  • If you implement a factory class with a method that returns the singleton instance, you allow yourself flexibility in the runtime class of the return value, which can be either MySingleton or a subclass thereof. You may have to make the constructor nonprivate to make that work.
  • You can have a SingletonFactory class with a globally accessible map of class names or Class objects to singleton instances. Again, the runtime type of the instances can be either the type indicated by the class name or a subclass, and the constructor will not be private.

For other possible implementations, see "Implementing the Singleton Pattern in Java" in Resources. As I discuss the singleton, keep the above implementations in mind, although many of those phenomena can occur for any implementation of the singleton.

Now that we've looked briefly at implementation, let's turn to the heart of this article: how two singletons can exist simultaneously.

Multiple singletons in two or more virtual machines

When copies of the singleton class run in multiple VMs, an instance is created for each machine. That each VM can hold its own singleton might seem obvious but, in distributed systems such as those using EJBs, Jini, and RMI, it's not so simple. Since intermediate layers can hide the distributed technologies, to tell where an object is really instantiated may be difficult.

For example, only the EJB container decides how and when to create EJB objects or to recycle existing ones. The EJB may exist in a different VM from the code that calls it. Moreover, a single EJB can be instantiated simultaneously in several VMs. For a stateless session bean, multiple calls to what appears, to your code, to be one instance could actually be calls to different instances on different VMs. Even an entity EJB can be saved through a persistence mechanism between calls, so that you have no idea what instance answers your method calls. (The primary key that is part of the entity bean spec is needed precisely because referential identity is of no use in identifying the bean.)

The EJB containers' ability to spread the identity of a single EJB instance across multiple VMs causes confusion if you try to write a singleton in the context of an EJB. The instance fields of the singleton will not be globally unique. Because several VMs are involved for what appears to be the same object, several singleton objects might be brought into existence.

Systems based on distributed technologies such as EJB, RMI, and Jini should avoid singletons that hold state. Singletons that do not hold state but simply control access to resources are also not appropriate for EJBs, since resource management is the role of the EJB container. However, in other distributed systems, singleton objects that control resources may be used on the understanding that they are not unique in the distributed system, just in the particular VM.

Multiple singletons simultaneously loaded by different class loaders

When two class loaders load a class, you actually have two copies of the class, and each one can have its own singleton instance. That is particularly relevant in servlets running in certain servlet engines (iPlanet for example), where each servlet by default uses its own class loader. Two different servlets accessing a joint singleton will, in fact, get two different objects.

Multiple class loaders occur more commonly than you might think. When browsers load classes from the network for use by applets, they use a separate class loader for each server address. Similarly, Jini and RMI systems may use a separate class loader for the different code bases from which they download class files. If your own system uses custom class loaders, all the same issues may arise.

If loaded by different class loaders, two classes with the same name, even the same package name, are treated as distinct -- even if, in fact, they are byte-for-byte the same class. The different class loaders represent different namespaces that distinguish classes (even though the classes' names are the same), so that the two MySingleton classes are in fact distinct. (See "Class Loaders as a Namespace Mechanism" in Resources.) Since two singleton objects belong to two classes of the same name, it will appear at first glance that there are two singleton objects of the same class.

Singleton classes destroyed by garbage collection, then reloaded

When a singleton class is garbage-collected and then reloaded, a new singleton instance is created. Any class can be garbage-collected when no other object holds reference to the class or its instances. If no object holds a reference to the singleton object, then the singleton class may disappear, later to be reloaded when the singleton is again needed. In that case, a new singleton object will be created. Any static or instance fields saved for the object will be lost and reinitialized.

This problems exists in older VMs. JDK 1.2 VMs, in particular, conform to a newer class garbage collection model that forbids any class in a given classloader to be collected until all are unreferenced (see Programming Java threads in the real world, Part 7" in Resources). You can avoid class garbage collection in the older VMs by holding a reference to the singleton class or object in some other object that persists for the program's life. You can also set your VM to have no class garbage collection (-Xnoclassgc on the JRE 1.3, or -noclassgc on the IBM JVM). Keep in mind that if you have a long-running program that frequently reloads classes (perhaps through special class loaders such as the remote class loaders), you have to consider whether that could cause a problematic buildup of garbage classes in the VM.

Purposely reloaded singleton classes

Classes are reloaded not only after class garbage-collection; they can also be reloaded at Java programs' request. The servlet specifications allow servlet engines to do that at any time. When the servlet engine decides to unload a servlet class, it calls destroy(), then discards the servlet class; later, the servlet engine can reload the servlet class, instantiate the servlet object, and initialize it by calling init(). In practice, the process of unloading and reloading may occur in a servlet engine when a servlet class or JSP changes.

Like the previous two cases, the present case involves newly loaded classes. Here, however, classes are ditched on purpose, while a new copy of the class loads.

Depending on the servlet engine, when an old servlet class is discarded, the associated classes might not be, even if they have changed. So if a servlet gets a reference to a singleton object, you may find that there is one singleton object associated with the old servlet class and one associated with the new.

As servlet engines differ in their class-reloading policies, the singleton behavior is unpredictable unless you understand how your servlet engine's class-loading mechanisms work.

Similar problems can occur if you hold a reference from another object to a servlet and some chain of references keeps that object from the garbage collector. Then, when the servlet class should be discarded, it cannot be, and you may find the servlet class loaded twice in the VM.

Multiple instances resulting from incorrect synchronization

One of the common singleton implementations uses lazy initialization of the one instance. That means that the instance is not created when the class loads, but rather when it is first used. (See Listing 2.) A common mistake with that implementation is to neglect synchronization, which can lead to multiple instances of the singleton class. (See Listing 3.)

Listing 3

// error, no synchronization on method
public static MySingleton getInstance() {
    if (_instance==null) {
        _instance = new MySingleton();
    }
    return _instance;
}
1 2 Page
Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more