Wasn't sure which channel to ask this (<#C0B8Q383C...
# announcements
b
Wasn't sure which channel to ask this (#C0B8Q383C is a little dead), but I am curious about this KDoc on `LazyThreadSafetyMode.NONE`:
Copy code
/**
     * No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, its behavior is undefined.
     *
     * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread.
     */
Let's say my
lazy
field is calculated from
val
inputs on a data class by a deterministic, pure function. I don't mind potentially duplicating the work to calculate it in multiple threads, and would rather elide any synchronization costs. Is there any harm to using
NONE
in this case? Maybe some weirdness around Kotlin Native I haven't considered?
I would think that, regardless of
LazyThreadSafetyMode
, it should be possible to initialize the value into a
final
field and lean on the Java Memory Model to handle the memory barriers. (https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5) But again maybe this falls apart in native contexts
s
Lazy and final field seems contradictory
I think the only way to achieve lazy but avoid barriers on subsequent reads is to use the inner class trick
i
Is there any harm to using
NONE
in this case?
Yes, you may get NPE when accessing the value concurrently.
I don't mind potentially duplicating the work to calculate it in multiple threads, and would rather elide any synchronization costs.
The
PUBLICATION
mode is the best choice for that.
#C0B8Q383C channel is ok for such questions.