Do not read volatile _value field second time it is already initialized

This commit is contained in:
Ilya Gorbunov
2017-12-20 20:14:36 +03:00
parent 5d62277fa5
commit 934b3cc54e
+7 -2
View File
@@ -181,14 +181,19 @@ private class SafePublicationLazyImpl<out T>(initializer: () -> T) : Lazy<T>, Se
override val value: T override val value: T
get() { get() {
if (_value === UNINITIALIZED_VALUE) { val value = _value
if (value !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return value as T
}
val initializerValue = initializer val initializerValue = initializer
// if we see null in initializer here, it means that the value is already set by another thread // if we see null in initializer here, it means that the value is already set by another thread
if (initializerValue != null) { if (initializerValue != null) {
val newValue = initializerValue() val newValue = initializerValue()
if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) { if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) {
initializer = null initializer = null
} return newValue
} }
} }
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")