How to implement thread-safe lazy initialization?

后端 未结 12 825
一整个雨季
一整个雨季 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:58

    For singletons there is an elegant solution by delegating the task to the JVM code for static initialization.

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

    see

    http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

    and this blog post of Crazy Bob Lee

    http://blog.crazybob.org/2007/01/lazy-loading-singletons.html

提交回复
热议问题