A singleton pattern

The singleton mode is the simplest mode, but the lazy mode of the singleton mode will be thread unsafe when it is concurrent.

single thread  

        Singleton mode: Lazy mode thread is not safe

package com.wb.single;
public class Single {
    private static Single single = null;
    private Single() {




    }

    public static Single getInstance() {
        if (null == single) {
            single = new Single();
        }
        return single;
    }
}

Hungry Man Mode: Thread Safety

package com.wb.single;
public class Single1 {
    private static Single1 single1 = new Single1();
    private Single1() {



    }

    public static Single1 getInstance() {
        return single1;
    }
}

Safe Lazy Style:

package com.wb.single;
public class Single2 {
    private static Single2 single2 = null;
    private Single2() {



    }

    public static Single2 getInstance() {
        if (null == single2) {
            synchronized (Single2.class) {
                if (null == single2) {
                    single2 = new Single2();
                }
            }
        }
        return single2;
    }
}
Do your best, Pikachu

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324690715&siteId=291194637