From 934b3cc54e8c58f470cd2c929c014654ada61bbb Mon Sep 17 00:00:00 2001 From: Ilya Gorbunov Date: Wed, 20 Dec 2017 20:14:36 +0300 Subject: [PATCH] Do not read volatile _value field second time it is already initialized --- libraries/stdlib/src/kotlin/util/Lazy.kt | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/libraries/stdlib/src/kotlin/util/Lazy.kt b/libraries/stdlib/src/kotlin/util/Lazy.kt index 9b0ee761e2f..45192a97a2b 100644 --- a/libraries/stdlib/src/kotlin/util/Lazy.kt +++ b/libraries/stdlib/src/kotlin/util/Lazy.kt @@ -181,14 +181,19 @@ private class SafePublicationLazyImpl(initializer: () -> T) : Lazy, Se override val value: T get() { - if (_value === UNINITIALIZED_VALUE) { - val initializerValue = initializer - // if we see null in initializer here, it means that the value is already set by another thread - if (initializerValue != null) { - val newValue = initializerValue() - if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) { - initializer = null - } + val value = _value + if (value !== UNINITIALIZED_VALUE) { + @Suppress("UNCHECKED_CAST") + return value as T + } + + val initializerValue = initializer + // if we see null in initializer here, it means that the value is already set by another thread + if (initializerValue != null) { + val newValue = initializerValue() + if (valueUpdater.compareAndSet(this, UNINITIALIZED_VALUE, newValue)) { + initializer = null + return newValue } } @Suppress("UNCHECKED_CAST")