java foundation - thread-safe singleton lazy man

package savesingleton;
/*
Single synchronous mode embodiment lazy rewritten into thread-safe

@author zsben
@create 2020-01-03 22:22
*/

class Bank{

    private  Bank(){}

    private  static Bank instance = null;

    /*public static synchronized Bank getInstance(){
        if(instance == null){
            instance = new Bank();
        }
        return instance;
    Less efficient}
    */

    // efficient way: inside and outside each sentenced to a 
    public  static Bank getInstance () {
         IF (instance == null ) {
             // there must be a judge again: think about why, plus a layer is to prevent multiple threads at the same time to enter , the inner layer together with 
            the synchronized (Bank. class ) {
                 IF (instance == null ) {
                    instance = new Bank();
                }
            }
        }
        return instance;
    }

}

Guess you like

Origin www.cnblogs.com/zsben991126/p/12148319.html