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

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();
主站蜘蛛池模板: 淮安市| 兴化市| 周至县| 塔城市| 张北县| 西贡区| 宜宾市| 安徽省| 靖州| 阳春市| 淳安县| 龙里县| 贺兰县| 会昌县| 攀枝花市| 延长县| 准格尔旗| 个旧市| 靖江市| 常宁市| 舞钢市| 綦江县| 云林县| 浮山县| 江阴市| 赣州市| 蛟河市| 南汇区| 双牌县| 金门县| 东明县| 玉环县| 汉沽区| 石河子市| 商洛市| 图们市| 资溪县| 高尔夫| 玉门市| 赫章县| 鱼台县|