0

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;
    }


}
JavaSa
  • 5,813
  • 16
  • 71
  • 121
  • 1
    possible duplicate of [What is an efficient way to implement a singleton pattern in Java?](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java) – Don Roby Mar 01 '14 at 19:33
  • 2
    I see no difference between these implementations. The static fields are initialized at the same time as static blocks are executed (on class load). – poroszd Mar 01 '14 at 19:45

6 Answers6

3

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.

sakura
  • 2,249
  • 2
  • 26
  • 39
1

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;
   }
Varun
  • 1,014
  • 8
  • 23
  • Heard of that but please refer to my original question its about understanding the mechanics of java in my particular examples which are also legitimate by the way ,at least the first – JavaSa Mar 01 '14 at 19:39
  • 1
    @JavaSa Title of the question reads "What is right implementation of Singleton". If you are only asking about the difference, then I would say there is none. By the time getInstance() method is called the instance is already created in both the ways. – Varun Mar 01 '14 at 19:45
1

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.

Community
  • 1
  • 1
Markus
  • 763
  • 7
  • 24
0

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.

Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
  • @ Awfully awesome : Please look at http://www.oodesign.com/singleton-pattern.html First example I wrote mentioned there and therefore looks fine according to this site – JavaSa Mar 01 '14 at 19:41
  • @sakura: He asked the right way of implementing Singleton, and though I wouldn't recommend using Singleton at all, I believe that Lazy Instantiation of Singleton is one proper way, aside from using Enum. – Aman Agnihotri Mar 01 '14 at 19:41
  • @AwfullyAwesome you should mention that it is not thread safe. – poroszd Mar 01 '14 at 19:43
  • @JavaSa: Your mentioned approaches will work just as fine too. – Aman Agnihotri Mar 01 '14 at 19:44
  • 1
    @AwfullyAwesome: ok so why are they not correct? By the way I've asked about differences between two implementations I wrote, I think they are equal, what do you think this question is probably more about static initilizers in java – JavaSa Mar 01 '14 at 19:47
  • 1
    @JavaSa: I didn't say your mentioned implementations are wrong. I just said that they aren't the right way. When you initialize a static variable of any class outside any method, it starts occupying space in the memory when the program is run, even though it may never be used by your program. Lazily initializing your objects is nice way to keep such scenario in check. And both your mentioned snippets are functionally same. – Aman Agnihotri Mar 01 '14 at 19:50
0

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;
    }
}
RMachnik
  • 3,598
  • 1
  • 34
  • 51
0

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;
}
Sami Eltamawy
  • 9,874
  • 8
  • 48
  • 66