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 | class ThreadSafeLazyExample { |