zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    B. Xor of 3 题解(思维+构造)
    小 L 与 GCD 题解(数学 hard)
    F. Clear The Matrix 题解(状压dp)
    小顶堆与大顶堆的自定义cmp函数
    字符指针、字符数组
    python中创建dict对象
    中缀表达式转后缀表达式
    vue中keep-alive,include的缓存问题
    vue 冒号 :、@、# 是什么意思? v-bind v-on v-slot v-是指令
    vue 自定义指令 v-
  • 原文地址:https://www.cnblogs.com/chengmuyu/p/9630132.html
Copyright © 2011-2022 走看看