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) {
       
    }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值