首页 > 技术文章 > Kotlin Lazy延迟初始化

naray 2021-07-06 19:30 原文

一、by Lazy 延迟初始化是线程安全吗?

Lazy是线程安全的,系统默认给Lazy属性添加了同步锁。也就是LazyThreadSafetyMode.SYNCHRONIZED,使之在同一时刻只能有一个线程对Lazy属性初始化操作。

/**
 * Specifies how a [Lazy] instance synchronizes initialization among multiple threads.
 */
public enum class LazyThreadSafetyMode {

    /**
     * Locks are used to ensure that only a single thread can initialize the [Lazy] instance.
     */
    SYNCHRONIZED,

    /**
     * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value,
     * but only the first returned value will be used as the value of [Lazy] instance.
     */
    PUBLICATION,

    /**
     * No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined.
     *
     * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread.
     */
    NONE,
}

 

推荐阅读