Kotlin Lazy延迟初始化

一、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,
}

 

上一篇:ahk之路:利用ahk在window7下实现窗口置顶


下一篇:java jdk1.8 32/64位 官方绿色版下载附安装教程