/**
* Creates a new instance of the [Lazy] that uses the specified initialization function [initializer]
* and the default thread-safety mode [LazyThreadSafetyMode.SYNCHRONIZED].
*
* If the initialization of a value throws an exception, it will attempt to reinitialize the value at next access.
*
* Note that the returned instance uses itself to synchronize on. Do not synchronize from external code on
* the returned instance as it may cause accidental deadlock. Also this behavior can be changed in the future.
*/
public actual fun <T> lazy(initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer)
上面的函数体为 lazy 的实现代码,该函数的参数为接收一个无参并返回值为 T 类型的函数,然后它的实现是 SynchronizedLazyImpl
private class SynchronizedLazyImpl<out T>(initializer: () -> T, lock: Any? = null) : Lazy<T>, Serializable {
private var initializer: (() -> T)? = initializer
// 用内存可见性来检查是否在其他线程初始化过,这样来保证多线程安全
@Volatile private var _value: Any? = UNINITIALIZED_VALUE
// final field is required to enable safe publication of constructed instance
private val lock = lock ?: this
// 重写 get 来保证懒加载,只在使用的时候才执行函数
override val value: T
get() {
val _v1 = _value
// 如果不为默认值则说明被其他线程或该线程已经初始化过,这也就是 lazy 只执行一次后续直接取值的原因
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
// 转为 T 类型返回
return _v1 as T
}
return synchronized(lock) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
} else {
// lazy 返回值为该函数的执行结果
val typedValue = initializer!!()
_value = typedValue
initializer = null
typedValue
}
}
}
// 判断是否初始化过
override fun isInitialized(): Boolean = _value !== UNINITIALIZED_VALUE
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
private fun writeReplace(): Any = InitializedLazyImpl(value)
}
网友评论