• 单例模式


    保持线程安全的高性能单例模式:双检锁机制:

    public class Singleton {  
      //volatile使主内存变动实时刷新,懒加载模式
    private volatile static Singleton singleton;
      //将构造函数设置为private,阻止其他类直接实例化此类。
    private Singleton (){} public static Singleton getSingleton() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }

     保持线程安全的非lazy加载实现单例模式:

    public class Singleton {  
        private static Singleton instance = new Singleton();  
        private Singleton (){}  
        public static Singleton getInstance() {  
        return instance;  
        }  
    }

     使单例模式在进行反序列化之后依然有效,同时保持线程安全:借助枚举类(官方推荐):

    public enum SingleEnum implements Serializable {
        INSTANCE;
        private SingleEnum(){}
        private String content;
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String content) {
            this.content = content;
        }
    }

    获取单例:

    SingleEnum singleEnum = SingleEnum.INSTANCE;

    验证使用此方式在反序列化后得到的对象仍是同一个:

    public class EnumTest {
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            SingleEnum singleBean = SingleEnum.INSTANCE;
            SingleEnum singleBean2 = null;
            singleBean.setContent("单例,你好");
            System.out.println("实例化前的内容为"+singleBean.getContent());
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("singlebean.obj"));
            objectOutputStream.writeObject(singleBean);
            objectOutputStream.flush();
            FileInputStream fileInputStream = new FileInputStream("singlebean.obj");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            singleBean2 = (SingleEnum) objectInputStream.readObject();
            System.out.println("实例化后的内容为:"+singleBean2.getContent());
            Boolean flag = singleBean == singleBean2;
            System.out.println("是否相等:"+ flag);
    
        }
    }

    运行结果:

  • 相关阅读:
    Linux下chkconfig命令详解
    几种主流的快照技术
    HANA内存数据库与oracle数据库的性能比较
    计算机网络知识汇总
    bzoj1211: [HNOI2004]树的计数 prufer序列裸题
    1003: [ZJOI2006]物流运输 最短路+dp
    HDU
    2243: [SDOI2011]染色 树链剖分+线段树染色
    bzoj1036: [ZJOI2008]树的统计Count 树链剖分
    bzoj1042: [HAOI2008]硬币购物 dp+容斥
  • 原文地址:https://www.cnblogs.com/kongieg/p/12492372.html
Copyright © 2020-2023  润新知