君子兰槐的博客

不怨天不尤人。知行合一。致良知。

0%

Can't find blockingLazy() method in kotlin

In the ‘Standard Delegates’ section of the Delegation Properties page, there is one sentence says:

If you want thread safety, use blockingLazy() instead: it guarantees that the values will be computed only in one thread and that all threads will see the same value.

But I searched the kotlin standard library and can’t find the blockingLazy() method.

I was using the kotlin 1.9.10:

$ kotlin -version
Kotlin version 1.9.10-release-459 (JRE 17.0.8+9-LTS-211)

and kotlin standard library 1.9.0:

<dependency>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-stdlib</artifactId>
    <version>1.9.0</version>
</dependency>

It seems that kotlin has removed the blockingLazy method.

I did find a lazy method which allow passing a lock parameter. It should be the new way to use a blocking lazy.

So I implement a thread-safe version here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class ThreadSafeLazyExample {
init {
println("Created!")
}

private val lazyLock: Int = 1

// a thread safe lazy
val lazyStr: String by lazy(lazyLock) {
println("computed!")
"my lazy"
}
}

fun main() {
val sample = ThreadSafeLazyExample()
println("lazyStr is ${sample.lazyStr}")
println(" =${sample.lazyStr}")
}