码迷,mamicode.com
首页 > 编程语言 > 详细

实现线程安全的单例模式

时间:2017-08-29 14:21:20      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:inter   err   prot   logs   private   stream   create   handler   sleep   

一、双检查锁机制

package singleton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 双检查锁机制--单例模式
 * Created by daizengjie on 2017/8/29.
 */
public class MySingleton {

    private static final Logger logger = LoggerFactory.getLogger(MySingleton.class);

    //使用volatile关键字会强制将修改值写入主存
    //并发三要素:原子性(synchronized,Lock)、可见性(volatile)、有序性(重排序,happens-before原则,valotile)

    //Lock lock = new ReentrantLock()
    //lock.lock()
    //lock.unlock()   try..finally..

    volatile private static MySingleton instance = null;

    private MySingleton(){}

    public static MySingleton getInstance(){
        try {
            if(instance != null){//懒汉式

            }else{
                //准备性耗时
                Thread.sleep(300);
                synchronized (MySingleton.class){
                    if(instance == null){//二次检查
                        instance = new MySingleton();
                    }
                }
            }
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        return instance;
    }
}

二、内部类实现

package singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * 内部类实现单例模式
 * 反序列化与序列化前,需要同一个实例
 * Created by daizengjie on 2017/8/29.
 */
public class InnerClassSingleton implements Serializable{

    private static final long serialVersionUID = 1L;

    //内部类
    private static class MySingletonHandler{
        private static InnerClassSingleton instance = new InnerClassSingleton();
    }

    private InnerClassSingleton(){}

    public static InnerClassSingleton getInstance(){
        return MySingletonHandler.instance;
    }

    //反序列化之前会被调用
    protected Object readResolve() throws ObjectStreamException{
        return MySingletonHandler.instance;
    }
}

 

实现线程安全的单例模式

标签:inter   err   prot   logs   private   stream   create   handler   sleep   

原文地址:http://www.cnblogs.com/daizengjie/p/7447482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!