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

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();
主站蜘蛛池模板: 湖口县| 阳原县| 高州市| 阿勒泰市| 合肥市| 肃宁县| 荃湾区| 安远县| 岑溪市| 容城县| 湖南省| 邹平县| 措美县| 忻城县| 法库县| 日土县| 伽师县| 临海市| 丁青县| 黎城县| 青浦区| 盐亭县| 武强县| 启东市| 山东省| 隆安县| 杭锦后旗| 新蔡县| 祥云县| 阿城市| 上杭县| 武鸣县| 巴东县| 南召县| 兴业县| 潮安县| 恩施市| 三河市| 达孜县| 正安县| 沅江市|