How to implement thread-safe lazy initialization?

后端 未结 12 824
一整个雨季
一整个雨季 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 05:00

    class Foo {
      private volatile Helper helper = null;
      public Helper getHelper() {
        if (helper == null) {
          synchronized(this) {
            if (helper == null) {
              helper = new Helper();
            }
          }
        }
      return helper;
    }
    

    This is called double checking! Check this http://jeremymanson.blogspot.com/2008/05/double-checked-locking.html

提交回复
热议问题