Question

What is the difference between two implementation in java, which is the correct and why?

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

    private Singleton()
    {
        System.out.println("Singleton(): Initializing Instance");
    }

    public static Singleton getInstance()
    {    
        return instance;
    }

}

Or

class Singleton
{
    private static Singleton instance; 

    static
    {
        instance = new Singleton();
    }  

    private Singleton()
    {
        System.out.println("Singleton(): Initializing Instance");
    }

    public static Singleton getInstance()
    {    
        return instance;
    }


}

No correct solution

OTHER TIPS

First coming to your question,

AFAIK, both code snippets are same. I don't see any difference.

However, As other answers have suggested there are better ways to create Singleton implementation. But that would be bit off-topic to your question and internet (google) is your best friend to find it out.

No difference. In both cases you are eagerly creating an instance and by the time getInstance() is called, the instance is ready.

But if you are looking for a easy and good implementation of singleton,

Better use an enum to implement Singleton

public enum Singleton {
       INSTANCE;
   }

My answer bases on this article about singleton: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

  1. Your first example should always work but does not allow lazy init.
  2. In a single threaded environment you could implement a singleton like in "my" first example.
  3. In a multi-threaded environment with Java 1.5 and referenced mutable objects you could use "my" second example.
  4. Useful stackoverflow answer/articles:

Example 1:

class SingleSingleton { 

    private Helper helper = null;

    public Helper getHelper() {
        if (helper == null) 
            helper = new Helper();
        return helper;
    }
}

Example 2:

class MultiSingletonJDK5 {
    private volatile Helper helper = null;

    public Helper getHelper() {
        if (helper == null) {
            synchronized(this) {
                if (helper == null)
                    helper = new Helper();
            }
        }
        return helper;
    }
}

I hope this helps. If not, give us some details or more background.

Both implementations are not correct, also static qualifier are not quite good practice at all :) There are my suggestion of Singletns:

public final class LazySingleton {
    private static volatile LazySingleton instance = null;

    // private constructor
    private LazySingleton() {
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                instance = new LazySingleton();
            }
        }
        return instance;
    }
}

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;

    // private constructor
    private EagerSingleton() {
    }

    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }
}

Generally, Singleton design pattern concept is based on having only single instance of your class. This could be reached through two main aspects:

1) Having a private constructor for your class to prevent any outer class to call it and re-create the instance. This could be reached as the following:

private Singleton()
{
    System.out.println("Singleton(): Initializing Instance");
}

2) Having a static method that allow you to retrieve the initialized instance or initialize it if it is not initialized yet as @Awfully Awesome mentioned in his answer:

public static Singleton newInstance()
{
if (singleton == null)
{
  singleton = new Singleton();
}

return singleton;
}

Both the mentioned methods are not the right way of applying Singleton pattern.

Here's the right way. The Lazy-Instantiation way:

public class Singleton
{
  private static Singleton singleton;

  private Singleton()
  {
  }

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

    return singleton;
  }
}

The getInstance() method lazily instantiates Singleton object when its called the first time. So the Singleton object isn't present in the memory, till the moment its required.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top