When is a Singleton not a
Singleton? - JavaWorld January 2001
Tutorial Details:
When is a singleton not a singleton?
When is a singleton not a singleton?
By: By Joshua Fox
Avoid multiple singleton instances by keeping these tips in mind
he 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 Frame s 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 garbag
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: When is a Singleton not a
Singleton? - JavaWorld January 2001
View Tutorial: When is a Singleton not a
Singleton? - JavaWorld January 2001
Related
Tutorials:
Object-oriented
language basics, Part
7
Object-oriented
language basics, Part
7 |
Cut down on
logging errors with Jylog
Cut down on
logging errors with Jylog |
XSLT blooms with
Java
XSLT blooms with
Java |
Write once,
persist anywhere
Write once,
persist anywhere |
Cache SOAP services on
the client side
Cache SOAP services on
the client side |
Create your own type 3 JDBC driver, Part 3
Create your own type 3 JDBC driver, Part 3 |
Check out three
collections libraries
Check out three
collections libraries |
Profiling CPU
usage from within a Java application
Profiling CPU
usage from within a Java application |
Sort it
out
Sort it
out |
My kingdom for
a good timer!
My kingdom for
a good timer! |
Attack of the
clones
Attack of the
clones |
Manage users with
JMS
Manage users with
JMS |
Simply
Singleton
Simply
Singleton |
High-availability mobile applications
High-availability mobile applications |
Impressive
!
Impressive
! |
Good, but
obsolete
Good, but
obsolete |
Mandarax
Mandarax is an open source java class library for deduction rules. It provides an infrastructure for defining, managing and querying rule bases. |
Tech Tip: Using the Varargs Language Feature
Have you ever needed to pass in many instances of the same object type to a method, but you don't know at compile time how many instances there will be? Find out how the new varargs language feature makes it easy to handle situations like this. |
istory of Bioinformatics
istory of Bioinformatics
History of Bioinformatics
The Modern bioinformatics is can be classified into two broad categories, Bi ological Science and computational Science . Here is the data of hi storical events for both biology and computer |
New Technical Articles: 64-bit Programming on Solaris 10 OS for x86 Platforms
Four technical articles describe the new Sun Studio 10 software's 64-bit programming features on the Solaris 10 OS for x86 and AMD64 platforms. Important issues regarding the AMD64 ABI (Application Binary Interface), debugging, migration to 64-bits, and p |
|
|
|