How to implement thread-safe lazy initialization?

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

    If you use lombok in your project, you can use a feature described here.

    You just create a field, annotate it with @Getter(lazy=true) and add initialization, like this: @Getter(lazy=true) private final Foo instance = new Foo();

    You'll have to reference field only with getter (see notes in lombok docs), but in most cases that's what we need.

提交回复
热议问题