The Singleton Pattern

A design pattern is a general solution to a common problem in software design. The idea is that the solution gets translated into code, and that the code can be applied in different situations where the problem occurs. Discussion of design patterns started with the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. These four authors are known as the "Gang of Four" or simply "GoF". In their book, the GoF categorized patterns into different subject areas, of which there are three primary areas: creational, structural, and behavioral. Creational patterns describe how objects are created (or "instantiated" in object-oriented terminology). Structural patterns offer help in how to connect and combine objects. Behavioral patterns describe algorithms or communication mechanisms. Some common pattern names are Singleton in the creational area, Observer in the behavioral area, and Facade in the structural area. This Tech Tip describes the Singleton pattern strictly in the context of the Java programming language.

One of the commonly used creational patterns is the Singleton pattern. It describes a technique for ensuring that only a single instance of a class is ever created. In essence, the technique takes the following approach: don't let anyone outside the class create instances of the object. Typically, Singletons are lazily created to reduce memory requirements until needed. You can implement this approach in many different ways.

If you know the one instance being created will be a subclass, make the parent class abstract and provide a method to get the current instance. An example of this is the Toolkit class in the AWT package. The constructor for Toolkit is public (the default constructor in this particular case):
   public Toolkit()

and the class has a getDefaultToolkit() method for getting the specific subclass -- in this case, the subclass is platform-specific:
   public static Toolkit getDefaultToolkit()
On a Linux platform with the Sun Java runtime, the specific subclass is of type sun.awt.X11.XToolkit. However you don't need to know that because you only access the class through its common abstract parent class, Toolkit.

The Collator class is another example of this pattern, with a slight difference. It offers two getInstance() methods. The no-argument version gets the Collator for the default locale. You can pass in your own locale to get the instance of the Collator for that locale. Request the Collator for the same locale multiple times and you get back the same Collator instance. The constructor itself is protected. Similar ways of restricting class creation can be found throughout the J2SE standard libraries.

At this point you might think that restricting access to the constructor of a class automatically makes it a Singleton. It doesn't. A case in point is the Calendar class. The Calendar class constructor is protected, and the class offers a getInstance() method to get an instance of the class. However, each call to getInstance() gets a new instance of the class. So that isn't a Singleton.

When you create your own Singleton class, make sure that only a single instance is ever created:
   public class MySingleton {
     private static final MySingleton INSTANCE = 
       new MySingleton();

     private MySingleton() {
     }

     public static final MySingleton getInstance() {
       return INSTANCE;
     }
   }
The static method, getInstance(), returns the single instance of the class. Note that even if the single instance needs to be a subclass, you don't have to change the API.

Theoretically, you don't need the getInstance() method because the INSTANCE variable could be public. However, the getInstance() method does provide flexibility in case of future system changes. Good virtual machine implementations should inline the call to the static getInstance() method.

That's not quite all there is to creating a Singleton. If you need to make your Singleton class Serializable, you must provide a readResolve() method:
  /\*\*
   \* Ensure Singleton class
   \*/
  private Object readResolve() throws ObjectStreamException {
    return INSTANCE;
  }
With the readResolve() method in place, deserialization results in the one (and only one) object -- the same object as produced by calls to the getInstance() method. If you don't provide a readResolve() method, an instance of the object is created each time you deserialize the object.

The Singleton pattern is useful if you know you only have a single resource, and need to share access to the state information of that single resource. Identifying the need for the Singleton pattern at design time can simplify development. However, sometimes you're not aware of the need until a performance problem leads you to refactor code and use the pattern at a later time. For example, you might discover that system performance is degrading because your program is repeatedly creating instances of the same class to pass along state information. By changing to the Singleton pattern, you avoid recreating the same object. This frees up time the system uses to recreate the object, and saves the time the garbage collector needs to free those instances.

In short, use the Singleton design pattern when you want to ensure that one, and only one, instance of a class is ever created. If your constructor doesn't require any operations, provide an empty private constructor (or a protected constructor if you need to subclass). Otherwise, by default, the system will provide a public constructor, something you don't want when working with a Singleton.

Note that Singletons are only guaranteed to be unique within a given class loader. If you use the same class across multiple distinct enterprise containers, you'll get one instance for each container.

A Singleton pattern is often used with another pattern called the Factory pattern. Like the Singleton pattern, the Factory pattern is a creational pattern. It describes how subclasses of a particular object, or more typically, implementers of a particular interface, do the actual object creation. A good example of the Factory pattern is the Swing BorderFactory class. The class has a series of static methods returning different types of Border objects. It hides the implementation details of the subclasses, allowing the factory to directly call the constructors for the interface implementations. Here's an example of BorderFactory in use:
   Border line = BorderFactory.createLineBorder(Color.RED);
   JLabel label = new JLabel("Red Line");
   label.setBorder(line);
Here, the fact that BorderFactory creates a LineBorder, or how BorderFactory does that, is hidden from the developer. In this particular example, you can directly call the LineBorder constructor, but in many cases of using the Factory pattern, you can't.

Frequently, the class implementing the Singleton pattern returns an object to use as a Factory to create instances of a different class. This is exemplified by the PopupFactory class in the way it creates Popup objects.

To get the Singleton factory, you call the getSharedInstance() method of PopupFactory:
   PopupFactory factory = PopupFactory.getSharedInstance();
Then you create a Popup object from the factory by calling the factory's getPopup() method, passing in the parent component, its contents, and position:

   Popup popup = factory.getPopup(owner, contents, x, y);
You'll find the Factory pattern used frequently in a security context. In the following example, a certificate factory is obtained for a particular algorithm, then a certificate for a stream is generated:
   FileInputStream fis = new FileInputStream(filename);
   CertificateFactory cf = 
      CertificateFactory.getInstance("X.509");
   Collection c = cf.generateCertificates(fis);
As shown with BorderFactory, the Factory pattern does not have to be used with the Singleton pattern. However the two patterns are frequently used together.

\*\*\*\*\*\*\*

Student Developers

Where can you find hot technologies, open-source communities, and job opportunities? Sun is looking for students who are ready to innovate and create the future. Read More.

Comments:

What is the difference between static class and singlton? What I mean by static class is the class whose methods are static. Why do we keep variable static in singleton pattern implementation ?

Posted by Rajiv Bhalani on February 14, 2008 at 04:22 AM PST #

the tip on readResolve is misleading. In the general case it is simply not true that the read will generate different instances. The same object is serialised the same object will be read! there will be only one instance on the receiving end.
Or am I wrong?

Posted by BERNARD AMADE on March 21, 2008 at 01:08 AM PDT #

Regarding the tip on readResolve(), the article points out the problem occurs on deserialization: "If you don't provide a readResolve() method, an instance of the object is created each time you deserialize the object."

Posted by Ed Zwart on March 26, 2008 at 02:37 AM PDT #

again this is not entirely true: once an instance is deserialized then no more instance will be created. The only problem could be if you deserialize AND call locally a getInstance() -or if you deserialize from different streams-.
For more comments about this see: http://groompf.blogspot.com/2048/02/may-happen-so-what-over-engineering.html

Posted by Bernard AMADE on March 29, 2008 at 03:04 AM PDT #

I guess the reason for declaring static variables in a Singleton class is for thread safety.

Check this out on
http://java-x.blogspot.com/2006/03/singleton-pattern-in-java.html

Such an implementation is thread safe because, the Java language specification (8.3.2 Initialization of fields) guarantees that the static member variables will be initialized exactly once.

Posted by trishul on April 07, 2008 at 11:39 PM PDT #

what is mean by singleton pattern... plz give some simple points

Posted by vishnukumar on August 07, 2008 at 09:34 PM PDT #

Post a Comment:
Comments are closed for this entry.
About

Java Technology Fundamentals are now covered as part of the Core Java Technology Tech Tips. Please go there for more tech tips.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today