PUBLICATION
Initializer function can be called several times on concurrent access to an uninitialized Lazy instance value, but only one computed value will be used as the value of a Lazy instance and will be visible by all threads.
Samples
import samples.assertPrints
import kotlin.concurrent.thread
fun main() {
//sampleStart
class Answer(val value: Int, val computedBy: Thread = Thread.currentThread()) {
override fun toString() = "Answer: $value, computed by: $computedBy"
}
val answer: Answer by lazy(LazyThreadSafetyMode.PUBLICATION) {
println("Computing the answer to the Ultimate Question of Life, the Universe, and Everything")
Answer(42)
}
val t1 = thread(name = "#1") {
println("Thread 1: $answer")
}
val t2 = thread(name = "#2") {
println("Thread 2: $answer")
}
// It is **not** guaranteed that 'Computing' message will be printed once,
// but guaranteed that both threads will see 42 computed by *the same* thread as an answer
t1.join()
t2.join()
//sampleEnd
}