How to implement thread-safe lazy initialization?

后端 未结 12 807
一整个雨季
一整个雨季 2020-11-28 04:13

What are some recommended approaches to achieving thread-safe lazy initialization? For instance,

// Not thread-safe
public Foo getI         


        
12条回答
  •  抹茶落季
    2020-11-28 04:50

    The easiest way is to use a static inner holder class :

    public class Singleton {
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            return Holder.INSTANCE;
        }
    
        private static class Holder {
            private static final Singleton INSTANCE = new Singleton();
        }
    }
    

提交回复
热议问题