- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 176字
- 2021-06-25 20:52:32
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();
- 數據科學實戰手冊(R+Python)
- SPSS數據挖掘與案例分析應用實踐
- jQuery Mobile Web Development Essentials(Third Edition)
- Apache ZooKeeper Essentials
- Python Deep Learning
- x86匯編語言:從實模式到保護模式(第2版)
- Reactive Programming With Java 9
- Xamarin.Forms Projects
- MySQL數據庫基礎實例教程(微課版)
- Java程序設計
- C#應用程序設計教程
- Visual Basic程序設計教程
- Unity 2018 Shaders and Effects Cookbook
- RESTful Web Clients:基于超媒體的可復用客戶端
- scikit-learn Cookbook(Second Edition)