Middle
Is lazy a thread-safe construct?
sobes.tech AI
Answer from AI
lazy in Kotlin is not thread-safe by default. Thread safety is achieved by specifying a special initialization mode.
Available modes (enumeration LazyThreadSafetyMode):
SYNCHRONIZED: Default. A lock is used to ensure that only one thread initializes the value at any given time. All threads see the same initialized value.PUBLICATION: Multiple threads can execute the initializer lambda simultaneously. The first thread to successfully initialize the value wins. Other results are ignored. Threads waiting for initialization will receive either the already initialized value or the value initialized by another thread.NONE: No thread safety guarantees. The fastest mode. Do not use this mode if there is a possibility of accessing the lazy property from multiple threads simultaneously.
Example of usage with explicit mode specification:
// Thread-safe mode SYNCHRONIZED (default)
val safeLazyValue: String by lazy {
// Initialization code
"Thread-safe string (SYNCHRONIZED)"
}
// Mode PUBLICATION - can be initialized by multiple threads, but the result will be one.
val publicationLazyValue: String by lazy(LazyThreadSafetyMode.PUBLICATION) {
// Initialization code
"Thread-safe string (PUBLICATION)"
}
// Non-thread-safe mode. Fast but dangerous for multithreading.
val unsafeLazyValue: String by lazy(LazyThreadSafetyMode.NONE) {
// Initialization code
"Non-thread-safe string (NONE)"
}