官术网_书友最值得收藏!

Early and lazy loading

Singletons can be split into two categories, depending on when the instance object is created. If the singleton is created when the application is started, it is considered an early/eager instantiation. Otherwise, if the singleton constructor is invoked when the getInstance method is invoked for the first time, it is considered a lazy-loading singleton.

The lock-free thread-safe singleton presented in the previous example is considered an early-loading singleton in the first version of Java. However, in the latest version of Java, classes are loaded when they are needed, so that version is also a lazy-loading version. Furthermore, the moment that a class is loaded depends on the JVM implementation and may differ from one version to another. Making design decisions based on JVM implementation should be avoided.

Currently, there is no reliable option in Java for creating an early loading singleton. If we really need an early instantiation, we should enforce it at the start of the application, by simply invoking the getInstance() method, as shown in the following code:

Singleton.getInstance();
主站蜘蛛池模板: 泽普县| 元江| 曲麻莱县| 星座| 贡觉县| 绍兴市| 鄂托克前旗| 农安县| 黔南| 喜德县| 宁都县| 肃宁县| 伊春市| 内江市| 武安市| 北流市| 牙克石市| 探索| 江城| 闸北区| 靖州| 乌兰浩特市| 双柏县| 运城市| 徐汇区| 金山区| 东宁县| 南溪县| 筠连县| 达孜县| 开平市| 江口县| 聂拉木县| 舟曲县| 镇安县| 大方县| 沁阳市| 正安县| 平阴县| 富锦市| 喀什市|