0

In this link i found the singleton instantiation as below:

public static Singleton getInstanceDC() {
        if (_instance == null) {                // Single Checked (1)
            synchronized (Singleton.class) {
                if (_instance == null) {        // Double checked
                    _instance = new Singleton();
                }
            }
        }
        return _instance;
}

I am not getting the point of single check ie (1) . Whats its use here any way the single thread will be checking the instance inside synchronized block , so what is point of using the first check?

Cœur
  • 37,241
  • 25
  • 195
  • 267
jayendra bhatt
  • 1,337
  • 2
  • 19
  • 41

1 Answers1

3

Consider that in a multithreaded environment two threads can access your singleton. Here is what can happen without a double check.

First thread enters getInstanceDC(); _instance is null so it enters the if block. Second thread enters getInstanceDC(); _instance is null so it enters the if block. First thread creates a new instance. Second thread creates a new instance.

The double check in a synchronized block solves this problem.

So why not synchronize the whole method? The answer is for performance reasons.

condorcraft110 II
  • 261
  • 1
  • 2
  • 15
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • but the second check is under synchronized block so only one thread will enter there at a time (since it has a Class class object lock), and by the time it comes out of the sync block the instance is created, so first check stays useless, isnt it so? – jayendra bhatt Mar 16 '15 at 17:31
  • 2
    The first check is out of synchronized block. Most of the times the check will say that _instance is already existent (not null). This check is done without synchronization, so is faster. – Davide Lorenzo MARINO Mar 16 '15 at 17:32
  • ohh.got it now..it will avoid needless stay in synchronized block..:) – jayendra bhatt Mar 16 '15 at 18:03