- 静态内部类(static nested class) 优先考虑
- public class LazySingleton{
- private LazySingleton(){}
- private static class Nested{
- private static final LazySingleton single = new LazySingleton();
- }
- public static LazySingleton getInstance(){
- return Nested.single;
- }
- }
双重检查锁定(DCL)
- public class LazySingleton{
- private LazySingleton(){}
- private static volatile LazySingleton single = null;
- public static LazySingleton getInstance(){
- if(single == null){
- synchronized (LazySingleton.class){
- if(single == null){
- single = new LazySingleton(); //① 非原子操作
- }
- }
- }
- return single;
- }
- }