Home  >  Article  >  Java  >  What does Holder refer to in java singleton mode?

What does Holder refer to in java singleton mode?

王林
王林forward
2023-04-29 11:13:151347browse

Difference

1. In the declaring class, member variables do not declare instance variables, but are placed in static inner classes. This approach is similar to that of a slacker. They all use a class loading mechanism to ensure that there is only one thread to initialize the instance. The difference is that the Holder single mode puts the initialization of the instance into a static category to achieve lazy loading.

The core of the Holder mode is static variables, which are convenient enough and thread-safe; holding real examples through the static Holder class indirectly implements lazy loading.

2. Features, realizes lazy loading, good performance and thread safety.

Example

public class Singleton {
      /**
       * 类级的内部类,也就是静态的成员式内部类,该内部类的实例与外部类的实例
       * 没有绑定关系,而且只有被调用到才会装载,从而实现了延迟加载
       */
      private static class SingletonHolder{
          /**
           * 静态初始化器,由JVM来保证线程安全
           */
         private static Singleton instance = new Singleton();
     }
     /**
      * 私有化构造方法
      */
     private Singleton(){
     }
     public static  Singleton getInstance(){
         return SingletonHolder.instance;
     }
 }

The above is the detailed content of What does Holder refer to in java singleton mode?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete