java单例问题

之前看资料,有人根据对象的创建时间将单例的实现分为懒汉式和饿汉式:

懒汉式:

 1 public class Singleton {
 2     private volatile static Singleton instance;
 3 
 4     private Singleton(){
 5             System.out.println("Singleton has loaded");
 6         }
 7 
 8     public static Singleton getInstance() {
 9         if (instance == null) {
10             synchronized (Singleton.class) {
11                 if (instance == null) {
12                     instance = new Singleton();
13                 }
14             }
15         }
16         return instance;
17     }
18 }

1 通过延迟加载,提高内存使用效率;

2 双重为空判断:第一个判断可以减少锁判断;第二个判断可以减少对象重复重复创建;

 

饿汉式:

 1 public class Singleton {
 2     // 通过静态实现单例,但是存在创建时间过早问题
 3     privatestatic Singleton instance = new Singleton();
 4 
 5     private Singleton(){
 6             System.out.println("Singleton has loaded");
 7         }
 8 
 9     public static Singleton getInstance() {
10         return instance;
11     }
12 }

1 代码精简;

2 通过静态实现在类加载时就创建对象,避免了同步问题;但是也造成实例化过早,存在内存浪费;

 

按需饿汉式:

public class Singleton {
    private Singleton(){
        System.out.println("Singleton has loaded");
    }

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

1 使用内部类来创建对象,实现延迟加载;

 

参考资料:

  https://baijiahao.baidu.com/s?id=1604691509810750218&wfr=spider&for=pc

posted @ 2018-09-11 20:35  橙木鱼  阅读(191)  评论(0编辑  收藏  举报