Is there a simple way get a delegated property by lazy
's value computed per thread like ThreadLocal
?
LazyThreadSafetyMode
controls concurrent initialization, with .NONE
coming close to the desired functionality by allowing multiple threads to receive different values, but has subsequent post initialization calls referencing the same object, returning the same singular value regardless of thread, with some cases returning null
.
Regardless of concurrent initialization, or late initialization, the property would cache a unique value per thread.
The Kotlin delegates are easy to extend with your own implementation.
You can make your delegate maintain a
ThreadLocal<T>
withinitialValue
calculated by the function that is passed:Or maintain a
Lazy<T>
per thread withThreadLocal<Lazy<T>>
, so that your delegate can implementLazy<T>
by itself:Here's a convenience function to create instances of the delegate:
Then just delegate a property to
threadLocalLazy { ... }
. Usage example: