Why to double check the singleton instantiation
Asked Answered
P

1

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?

Platinous answered 16/3, 2015 at 16:48 Comment(0)
S
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.

Sloganeer answered 16/3, 2015 at 16:53 Comment(3)
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?Platinous
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.Sloganeer
ohh.got it now..it will avoid needless stay in synchronized block..:)Platinous

© 2022 - 2024 — McMap. All rights reserved.