0

When designing a Singleton class, is it required to use double checking? Why can't I just put an if condition as well in the synchronize block? Or is there any break of it?

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

   return singleton;
}
CharlieB
  • 940
  • 7
  • 9
Rex
  • 149
  • 3
  • 10
  • This isn't double checking. (Oh I see, you did that on purpose. Double checking allows "faster access" in the case where the singleton is already created. It's an optimization, you don't *need* it.) – markspace May 02 '18 at 20:19
  • 3
    Use an `enum` to implement `Singleton`. The lazy initialization pattern is not particularly safe. – Elliott Frisch May 02 '18 at 20:19
  • You can, but if you have an `if` check _outside_ the sync block, you can avoid entering the sync block unnecessarily. Entering a sync block is expensive. – khelwood May 02 '18 at 20:19
  • 1
    Thanks @Khelwood , crisp and exactly what I was looking for. – Rex May 06 '18 at 15:42

2 Answers2

1

The check outside of the synchronized is not required, however, it will improve performance as long as you call getInstance() more than once. Using synchronized is very expensive, but just checking == null is very cheap. Usually, when you call getInstance(), there will already be an instance constructed, so if you always check == null first you can minimize the number of times you use synchronized.

Vitruvie
  • 2,327
  • 18
  • 25
0

Safe way is by using enums. Here is example

public enum SingletonEnum {

INSTANCE;

int value;

public int getValue() {

    return value;

    }

public void setValue(int value) {

    this.value = value;

    }
}

Main class

public class EnumDemo {

public static void main(String[] args) {

    SingletonEnum singleton = SingletonEnum.INSTANCE;

    System.out.println(singleton.getValue());

    singleton.setValue(2);

    System.out.println(singleton.getValue());

    }

}
Vadim Cote
  • 188
  • 2
  • 10