How to implement thread-safe lazy initialization?

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

    Put the code in a synchronized block with some suitable lock. There are some other highly specialist techniques, but I'd suggest avoiding those unless absolutely necessary.

    Also you've used SHOUTY case, which tends to indicate a static but an instance method. If it is really static, I suggest you make sure it isn't in any way mutable. If it's just an expensive to create static immutable, then class loading is lazy anyway. You may want to move it to a different (possibly nested) class to delay creation to the absolute last possible moment.

提交回复
热议问题