educative.io

Double-Checked Locking

Under the section “Double-Checked Locking”.

It is unclear why the method is still synchronized? As it would make the entire method thread-safe already. Wouldn’t making the method synchronized defeat the purpose of another synchronized block within it?

Am I missing something here or is the method incorrectly left to be synchronized?

// Create a static method for object creation
synchronized public static AirforceOneWithDoubleCheckedLocking getInstance() {

    // Only instantiate the object when needed.
    if (onlyInstance == null) {
        // Note how we are synchronizing on the class object
        synchronized (AirforceOneWithDoubleCheckedLocking.class) {
            if (onlyInstance == null) {
                onlyInstance = new AirforceOneWithDoubleCheckedLocking();
            }
        }
    }

    return onlyInstance;
}
1 Like

Right solving.
// Create a static method for object creation
public static AirforceOneWithDoubleCheckedLocking getInstance() {
// Only instantiate the object when needed.
if (onlyInstance == null) {
// Note how we are synchronizing on the class object
synchronized (AirforceOneWithDoubleCheckedLocking.class) {
if (onlyInstance == null) {
onlyInstance = new AirforceOneWithDoubleCheckedLocking();
}
}
}

return onlyInstance;

}