您好,欢迎来到爱问旅游网。
搜索
您的当前位置:首页singleton完美写法

singleton完美写法

来源:爱问旅游网

package com.june.study.design_pattens.singleton;

/**
 * 写一个完美的还真不容易,感谢良葛格老师!
 *
 * 1. 实例的private性质和static性质
 * 2. 构造器的private性
 * 3. 如果是lazy-init的话,需要注意线程安全性
 * 4. 看看线程安全性设计里,synchronized的位置;为什么判断两次instance==null呢!
 *
 * @author lijg fantaxy025025@126.com 
 * @date Feb 25, 2010 1:27:19 PM
 * @version V3.0
 */
public class LazyThreadSafeSongleton {
   
    private static LazyThreadSafeSongleton instance = null;
   
    private LazyThreadSafeSongleton(){
        //nothing here
    }
   
    /** 既然synchronized可以,lock也可以哦! */
    public static LazyThreadSafeSongleton getInstance(){
        if(instance == null){//one
            synchronized (LazyThreadSafeSongleton.class) {//here!
                if (instance == null) {//two
                    instance = new LazyThreadSafeSongleton();
                }
            }
        }
       
        return instance;
    }
   
}

 

package com.june.study.design_pattens.singleton;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LazyThreadSafeSingleton2 {
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
   
    private static LazyThreadSafeSingleton2 instance = null;
   
    private LazyThreadSafeSingleton2(){
        //nothing here
    }
   
    /** 既然synchronized可以,lock也可以哦! */
    public static LazyThreadSafeSingleton2 getInstance(){
        if(instance == null){//one
            reentrantReadWriteLock.writeLock().lock();
            try {
                if (instance == null) {
                    instance = new LazyThreadSafeSingleton2();
                }
            } catch (Exception e) {
                //sth here
            } finally{
                reentrantReadWriteLock.writeLock().unlock();
            }
        }
       
        return instance;
    }
   
}

 

package com.june.study.design_pattens.singleton;

public class NormalSingleton {

    private static NormalSingleton instance = new NormalSingleton();//here!
   
    private NormalSingleton(){
        //nothing here
    }
   
    public static NormalSingleton getInstance(){
        return instance;
    }
   
    public static void main(String[] args) {
       
    }

}

 

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务