web analytics
Google + RSS Feed

How to use Singleton Class ?

0

March 2, 2014 by admin

The Singleton’s purpose is to control object creation, limiting the number of obejcts to one only. 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.

Implementing Singletons:

Example 1:

The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:

// File Name: Singleton.java
public class Singleton {

   private static Singleton singleton = new Singleton( );

   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ }

   /* Static 'instance' method */
   public static Singleton getInstance( ) {
      return singleton;
   }
   /* Other methods protected by singleton-ness */
   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}

Here is the main program file where we will create singleton object:

// File Name: SingletonDemo.java
public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance( );
      tmp.demoMethod( );
   }
}

This would produce the following result:

demoMethod for singleton

Example 2:

Following implementation shows a classic Singleton design pattern:

public class ClassicSingleton {

   private static ClassicSingleton instance = null;
   protected ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}

The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

Here ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.

Difference between Singleton Pattern vs Static Class in Java

Singleton pattern  vs  Static Class (a class, having all static methods) is another interesting questions, which I missed while blogging about Interview questions on Singleton pattern in Java. Since both Singleton pattern and static class provides good accessibility, and they share some similarities e.g. both can be used without creating object and both provide only one instance, at very high level it looks that they both are intended for same task. Because of high level similarities, interviewer normally ask questions like, Why you use Singleton instead of Static Methods, or Can you replace Singleton with static class, and  what are differences between Singleton pattern and static in Java. In order to answer these question, it’s important to remember fundamental difference between Singleton pattern and static class, former gives you an Object, while later just provide static methods. Since an object is always much more capable than a method, it can guide you when to use Singleton pattern vs static methods.
In this Java article we will learn, where to use Singleton pattern in Java, and when static class is better alternative. By the way, JDK has examples of both singleton and static, and that too very intelligently e.g. java.lang.Math is a final class with full of static methods, on the other hand java.lang.Runtime is a Singleton class in Java. For those who are not familiar with Singleton design pattern or static class,  static class is a Java class, which only contains static methods, good examples of static class is java.lang.Math,which contains lots of utility methods for various maths function e.g. sqrt(). While Singleton classes are those, which has only one instance during application life cycle likejava.lang.Runtime.

When to use Static Class in place of Singleton in Java

Indeed there are some situations, where static classes makes sense than Singleton. Prime example of this is java.lang.Math which is not Singleton, instead a class with all static methods. Here are few situation where I think using static class over Singleton pattern make sense:
1) If your Singleton is not maintaining any state, and just providing global access to methods, than consider using static class, as static methods are much faster than Singleton, because of static binding during compile time. But remember its not advised to maintain state inside static class, especially in concurrent environment, where it could lead subtle race conditions when modified parallel by multiple threads without adequate synchronization.
You can also choose to use static method, if you need to combine bunch of utility method together. Anything else, which requires singles access to some resource, should use Singleton design pattern.

Difference between Singleton vs Static in Java

This is answer of our second interview question about Singleton over static. As I said earlier, fundamental difference between them is, one represent object while other represent a method. Here are few more differences between static and singleton in Java.
1) Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
2) One more difference between Singleton and static is, ability to override. Since static methods in Java cannot be overridden, they leads to inflexibility. On the other hand, you can override methods defined in Singleton class by extending it.
3) Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes, because you can pass mock object whenever Singleton is expected, e.g. into constructor or as method arguments.
4) If your requirements needs to maintain state than Singleton pattern is better choice than static class, because
maintaining  state in later case is nightmare and leads to subtle bugs.
5) Singleton classes can be lazy loaded if its an heavy object, but static class doesn’t have such advantages and always eagerly loaded.
6) Many Dependency Injection framework manages Singleton quite well e.g. Spring, which makes using them very easy.
These are some differences between static class and singleton pattern, this will help to decide between two, which situation arises. In next section we will when to choose Singleton pattern over static class in Java.

Advantage of Singleton Pattern over Static Class in Java

Main advantage of Singleton over static is that former is more object oriented than later. With Singleton, you can use Inheritance and Polymorphism to extend a base class, implement an interface and capable of providing different implementations. If we talk about java.lang.Runtime, which is a Singleton in Java, call to getRuntime() method return different implementations based on different JVM, but guarantees only one instance per JVM, had java.lang.Runtime an static class, it’s not possible to return different implementation for different JVM.
That’s all on difference between Singleton and static class in Java. When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.

IN Short :

1) Singleton class can be extended. Polymorphism can save a lot of repetition.
2) A Singleton class can implement an interface, which can come in handy when you want to separate implementation from API.
3)Singleton can be extended. Static not.
4)Singleton creation may not be threadsafe if it isn’t implemented properly. Static not.
5)Singleton can be passed around as an object. Static not.
6)Singleton can be garbage collected. Static not.
7)Singleton object stores in Heap but, static object stores in stack
8)We can clone the object of Singleton but, we can not clone the static class object
9)Singleton class follow the OOP(object oriented principles) but not static class
10)Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.

The big difference between a singleton and a bunch of static methods is that singletons can implement interfaces (or derive from useful base classes, although that’s less common IME), so you can pass around the singleton as if it were “just another” implementation.


0 comments »

Leave a Reply

Your email address will not be published. Required fields are marked *


× 2 = fourteen

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts