Singleton

There are some instances in the application where we have to use just one instance of a particular class. Let’s take up an example to understand this. A very simple example is say Logger, suppose we need to implement the logger and log it to some file according to date time. In this case, we cannot have more than one instances of Logger in the application otherwise the file in which we need to log will be created with every instance. Other example – One file system, one window manager, one printer spooler, one Test engine, one Input/Output socket and etc.

Lets see how to design a singleton class. This is lazy instantiation.


package mynotes.designPatterns.creational;

public class Singleton {

private static Singleton uniqueInstance;

// other useful instance variables here
 private Singleton() {
 }

public static Singleton getInstance() {
 if (uniqueInstance == null) {
 uniqueInstance = new Singleton();
 }
 return uniqueInstance;
 }
 // other useful methods here
}

uniqueInstance holds our ONE instance; remember, it is a static variable. Our constructor is declared private; only Singleton can instantiate this class. The getInstance() method gives us a way to instantiate the class and also to return an instance of it. Note that if we never need the instance, it never gets created; this is lazy instantiation.

Lazy instantiation of a Singleton class possesses  problem. In Multithreaded environment, this may fail and create more than one object. Suppose there are 2 threads t1 and t2 trying to run the getInstance (), t1 got a chance and ran the first line checking the instance was null, but then paused and now t2 got the chance to run and in one go ran the whole method creating the object. After that t1 got resumed and since the null check had already been validated it creats the object as well. So, in multithreaded environment this fails.

For multithreaded environments a fix will be by making getInstance() a synchronized method.

For most Java applications, we obviously need to ensure that the Singleton works in the presence of multiple threads. But, it looks fairly expensive to synchronize the getInstance() method:

  • Do nothing if the performance of getInstance() isn’t critical to your application.
  • Move to an eagerly created instance rather than a lazily created one. 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. See code below:

public class Singleton {

private static Singleton uniqueInstance = new Singleton();

private Singleton() {
 }

public static Singleton getInstance() {
 return uniqueInstance;
 }
 // other useful methods here
}

  • Use “doublechecked locking” to reduce the use of synchronization in getInstance(). With doublechecked 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.

package mynotes.designPatterns.creational;

public class Singleton {

private volatile static Singleton uniqueInstance;

private Singleton() {
 }

public static Singleton getInstance() {
 if (uniqueInstance == null) {
 synchronized (Singleton.class) {
 if (uniqueInstance == null) {
 uniqueInstance = new Singleton();
 }
 }
 }
 return uniqueInstance;
 }
 // other useful methods here
}

The volatile keyword ensures that multiple threads handle the uniqueInstance variable correctly when it is being initialized to the Singleton instance.

One problem with subclassing Singleton is that the constructor is private. You can’t extend a class with a private constructor. So, the first thing you’ll have to do is change your constructor so that it’s public or protected. But then, it’s not really a Singleton anymore, because other classes can instantiate it.

What’s the difference between a singleton class and a static class?
The answer is static class is one approach to make a class ‘Singleton’. We can create a class and declare it as ‘final’ with all the methods ‘static’ and constructor ‘private’. In this case, you can’t create any instance of class and can call the static methods directly. The advantage of this static approach is that it’s easier to use. The disadvantage of course is that if in future you do not want the class to be static anymore, you will have to do a lot of recoding. Also being static all the methods gets load at the class loading time and if some methods are resource consuming then it may hit performance.

The Singleton Pattern also gives us a global point of access, just like a global variable, but without the downsides.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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: