How to implements DCL without the key work volatitle?

Viewed 83
public  class DCL {
    private static DCL staticDcl;

    private final DCL finalDcl;

    private DCL(){
        //other init operation
        
        
        //the action must be last.
        finalDcl = this;
    }

    public static DCL getDCL() {

        if (staticDcl == null) {
            synchronized(DCL.class) {
                if (staticDcl == null) {
                    staticDcl = new DCL();
                }
            }
        }
        return staticDcl.finalDcl;
    }
}

can the above code run without any error in multithreading environment??

I want to use the key word final to implements the dcl not volatitle.

2 Answers

You may run into problems, see Why is volatile used in double checked locking?

I suggest to not use this pattern, but rather the static holder pattern (SHP), which guarantees all the mechanics you try to reproduce. And with SHP you don't even have to think about volatile because the JVM handles it directly for you.

public class DCL {
    private DCL(){
        //other init operation
    }

    public static DCL getDCL() {
        return Holder.INSTANCE;
    }

    private static final class Holder {
        private static final DCL INSTANCE = new DCL();
    }
}

Also note that private final DCL finalDcl; is redundant because you can just return the instance directly, there's no need to create a new field which equals this.

The benefit of this pattern is that INSTANCE is instantiated only when it is first referenced, i.e. when getDCL() is called. This is due to the nature of lazy class loading.

Yes, without volatile, it is potentially broken, you can read my other answer for an explanation.

It is rather weird that you have staticDcl and finalDcl. If you want to provide singletons via that DCL, you do not need both. You can read the beginning of this question on how to achieve that. It also discusses how you could achieve double check locking safety without volatile, but still with some special semantics like release/acquire.

Related