-1

Static Initialization using Singleton pattern - can it solve the multi threaded environment issue instead of explicitly going for lock block.

V.Sriram
  • 774
  • 1
  • 6
  • 12

2 Answers2

1

There are many ways to write a thread-safe singleton class. Let's take a look.

There are 3 things, that you might care about, when creating singleton:

  1. thread-safety
  2. throughput
  3. lazy loading
  4. ability to handle exceptions, thrown in constructor.

The most native implementation in the following:

public class Singleton {
     private static Singleton instance;

     private Singleton() {}

     public synchronized static Singleton getInstance() {
          if (instance == null) {
               instance = new Singleton();
          }
          return instance;
     }
}

The only disadvantage here, is that you synchronize each time, when calling getInstance(), and throughput will suffer, when multiple threads will call getInstance() in the same time.

Ok, the next solution is:

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public synchronized static Singleton getInstance() {
        return instance;
    }

It's thread safe, throughput is fine, but we lost lazy loading (instance will be created when class is loaded, but not when first getInstance()is called) and we can't handle exceptions from constructor.

Next:

public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private final static Singleton instance = new Singleton();

    }

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

This implementation is my favourite one. It's thread safe, throughput is perfect and its lazy. The only drawback is that you still have no ability to handle exceptions from constructor. Otherwise, use it.

If handling exceptions from constructor is critical, use double-check locking:

class Singleton {
    private static volatile Singleton instance;

    private Singleton() {}
    public Singleton getInstance() {
        if (instance == null) {
            synchronized(this) {
                if (instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}

Note, that it can be used only since Java 5, because of volatile key-word semantics.

0

You can implement thread safe singleton but there is cost to pay if the object is heavily used by different thread. Thread Safe C# Singleton Pattern and http://csharpindepth.com/Articles/General/Singleton.aspx#performance

Community
  • 1
  • 1
Nadeem
  • 194
  • 1
  • 1
  • 8