zoukankan      html  css  js  c++  java
  • [转]Number one:单例模式5种JAVA实现及其比较

    错误解法一:当处于多线程环境时,会出现竞争。

    public class Singleton1     
    {
        private Singleton1()
        {
        }
        int a =5;
        private static Singleton1 singleton1 = null;
        public static Singleton1 getSingleton1(){
            if(singleton1 == null){
                singleton1 = new Singleton1();
            }
            return singleton1;
        }
    }

    错误解法二:虽然加了锁,解决了多线程下的竞争。但是在创建后的每次访问都加锁,影响效率。

    public class Singleton2 {
        private Singleton2()
        {
        }
        int a =5;
        private static Singleton2 singleton2 = null;
        public static Singleton2 getSingleton2(){
            synchronized(Singleton2.class)
            {
                if(singleton2 == null){
                    singleton2 = new Singleton2();
                }
            }
            return singleton2;
        }
    }

    可行的解法三:在锁前面再加一个if判断将是一种可行的解法。

    public class Singleton3 {
        private Singleton3()
        {
        }
        int a =5;
        private static Singleton3 Singleton3 = null;
        public Singleton3 getSingleton3(){
            if(Singleton3 == null){
                synchronized(Singleton3.class)
                {
                    if(Singleton3 == null){
                        Singleton3 = new Singleton3();
                    }
                }
            }
            return Singleton3;
        }
    }

     推荐的解法4:利用静态构造函数

    public class Singleton4 {
        private Singleton4() {
        }
    
        private static Singleton4 Singleton4 = new Singleton4();
    
        public Singleton4 getSingleton4() {
            return Singleton4;
        }
    }


     推荐的解法5:实现按需创建实例,涉及语言特性

    public class Singleton5 {
        Singleton5() {
        }
    
        public Singleton5 getSingleton5() {
            return Nested.instance;
        }
        
        static class Nested{
            Nested(){
            }
            static Singleton5 instance = new Singleton5();
        }
    }
  • 相关阅读:
    手动为php安装memcached扩展模块
    Linux下程序包管理工具RPM
    【Hibernate】一级、二级缓冲
    MySQL的用户和权限介绍
    一步一步教你安装openstack
    LVS负载平衡集群(没成型)
    SQL Server等待事件—PAGEIOLATCH_EX
    ORACLE ANALYZE使用小结
    为什么你SQL Server中SQL日期转换出错了呢?
    SQL Server误设置max server memory处理小结
  • 原文地址:https://www.cnblogs.com/study-development/p/3521623.html
Copyright © 2011-2022 走看看