cdurham
08/11/2023, 7:19 PMby lazy(LazyThreadSafetyMode.NONE) to NPE in the case where two threads race to initialize the value? I thought the worst case was multiple creations 😕
override val value: T
get() {
if (_value === UNINITIALIZED_VALUE) {
_value = initializer!!()
initializer = null
}
@Suppress("UNCHECKED_CAST")
return _value as T
}cdurham
08/11/2023, 7:20 PMif condition before _value is set, one of the threads sets _value and then nulls the initializer before the second thread sets value, resulting in a NPEcdurham
08/11/2023, 7:22 PMPUBLICATION?xoangon
08/11/2023, 9:59 PMby lazy { } in the second thread just return the memoized value without calling the initializer function?Landry Norris
08/11/2023, 11:33 PMThread 1 Thread 2
check initialized check initialized
call initializer OS schedules other work
set _value
nullify initializer
return value call initializer (NPE)Landry Norris
08/11/2023, 11:34 PMxoangon
08/12/2023, 7:20 AMsynchronized could fix it: