美文网首页
Java单例模式,线程安全

Java单例模式,线程安全

作者: WilsonMing | 来源:发表于2016-03-24 21:48 被阅读127次
    • 懒汉式:线程安全,开销大
    public class Singleton{
     private static final Singleton singleton;
    private Singleton(){
      }
     public static final synchronized Singleton getInstance(){
        if(singleton==null){
         singleton=new Singleton();
        }
        return singleton;
     }
    }
    
    • 双重检查锁:线程安全,根据需求使用
    public class Singleton{
      private volatile static Singleton singleton;
      private Singleton(){
      }
      public static final Singleton getInstance(){
        if(singleton==null){
          synchronized(Singleton.class){
            if(singleton==null){
            singleton=new Singleton();
            }
          }
        }
       return singleton;
      }
    }
    
    
    • 静态内部类锁:线程安全,比较推荐
    public class Singleton{
    private Singleton(){
      }
    private static class Holder{
    public static final Singleton singleton=new Singleton();
    }
    public static final Single getInstance(){
    return Holder.singleton;
    }
    }
    
    • 饿汗式:线程安全,但没有实现懒加载
    public class Singleton{
     private static final Singleton singleton=new Singleton();
    private Singleton(){
      }
     public static final Singleton getInstance(){
     return singleton;
     }
    }
    
    • 枚举:线程安全,但比较少人用
    public class Singleton{
    public enum EasySingleton{
        INSTANCE;
    }
    }
    

    相关文章

      网友评论

          本文标题:Java单例模式,线程安全

          本文链接:https://www.haomeiwen.com/subject/dtirlttx.html