Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton in java

I just got to read the following code somewhere :

public class SingletonObjectDemo {

    private static SingletonObjectDemo singletonObject;
    // Note that the constructor is private
    private SingletonObjectDemo() {
        // Optional Code
    }
    public static SingletonObjectDemo getSingletonObject() {
        if (singletonObject == null) {
            singletonObject = new SingletonObjectDemo();
       }
       return singletonObject;
    }
}

I need to know what is the need of this part :

if (singletonObject == null) {
    singletonObject = new SingletonObjectDemo();
}

What if we do not use this part of code ? There would still be a single copy of SingletonObjectDemo, why do we need this code then ?

like image 905
Ishi Avatar asked Jul 17 '10 18:07

Ishi


1 Answers

On lazy vs eager initialization

The if statement is an implementation of the lazy initialization technique.

A more explicit version is as follows:

private boolean firstTime = true;
private Stuff stuff;

public Stuff gimmeStuff() {
   if (firstTime) {
      firstTime = false;
      stuff = new Stuff();
   }
   return stuff;
}

What happens is that the very first time gimmeStuff() is invoked, firstTime would be true, so stuff would be initialized to new Stuff(). On subsequent invokations, firstTime would be false, so new Stuff() would no longer be called.

Thus, stuff is initialized "lazily". It's not actually initialized until the very first time it's needed.

See also

  • Wikipedia/Lazy initialization
  • Wikipedia/Initialization on demand holder idiom

On thread safety

It needs to be said that the snippet is not thread-safe. If there are multiple threads, then in some race conditions new SingletonObjectDemo() may be invoked several times.

One solution is to make synchronized getSingletonObject() method. This does, however, have a synchronization overhead on ALL calls to getSingletonObject(). The so-called double-checked locking idiom is then used to try to remedy this, but in Java, this idiom does not actually work until J2SE 5.0 with the introduction of volatile keyword in the new memory model.

Needless to say that proper enforcement of singleton pattern isn't a trivial thing.

See also

  • developerWorks/Java: Double-checked locking and the Singleton pattern -- A comprehensive look at this broken programming idiom
  • Wikipedia/Double-checked locking

Related questions

  • synchronized block vs synchronized method?

Effective Java 2nd Edition

Here's what the book has to say on these subjects:

Item 71: Use lazy initialization judiciously

As is the case for most optimizations, the best advice for lazy initialization is "don't do it unless you need to". Lazy initialization is a double-edged sword. It decreases the cost of initializing a class or creating an instance, at the expense of increasing the cost of accessing a lazily initialized field. Depending on what fraction of lazily initialized fields eventually require initialization, how expensive it is to initialize them, and how often each field is accessed, lazy initialization (like many "optimizations" actually harm performance).

In the presence of multiple threads, lazy initialization is tricky. If two or more threads share a lazily initialized field, it is critical that some form of synchronization be employed, or severe bugs can result.

Under most circumstances, normal initialization is preferable to lazy initialization.

Item 3: Enforce the singleton property with a private constructor or an enum type

As of release 1.5. there is a third approach to implementing singletons. Simply make an enum type with one element. [...] This approach is functionally equivalent to the public field approach, except that it's more concise, provides the serialization mechanism for free, and provides ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection-based attacks.

[...] A single-element enum type is the best way to implement a singleton.

Related questions

On enum singleton/Java implementation:

  • Efficient way to implement singleton pattern in Java
  • Java Enum Singleton
  • Comparing Java enum members: == or equals() ?
  • Thread safety in Singleton

On singleton pattern merits and alternatives:

  • On Design Patterns: When to use the Singleton?
  • Purpose of singletons in programming
  • What is so bad about Singletons
  • Singletons: good design or a crutch?
  • What’s Alternative to Singleton
  • Singleton: How should it be used
like image 129
polygenelubricants Avatar answered Oct 04 '22 03:10

polygenelubricants