I’m having trouble understanding the Kotlin/Native...
# multiplatform
c
I’m having trouble understanding the Kotlin/Native global immutability model, specifically for an iOS/Android shared library. I basically want to do a one-time initialization on a singleton to register an API key, and the only way I could get the iOS tests to pass was by using
@ThreadLocal
on the companion object and
@SharedImmutable
on the value to be initialized once. But that
@ThreadLocal
annotation makes me think that another thread might try to access the shared object and have it not be there, does the
@SharedImmutable
mean that each thread-local companion object will reference the same API key after initialization? Here’s basically what I’ve got
Copy code
class SingletonConfiguration
private constructor(
    val apiKey: String
) {

    @ThreadLocal
    companion object {
        @SharedImmutable
        lateinit var instance: SingletonConfiguration

        fun init(apiKey: String) : SingletonConfiguration {
            instance = SingletonConfiguration(apiKey)
            return instance
        }
    }
}
d
Hmm consider using
AtomicReference
and discard the
@ThreadLocal
.
k
ThreadLocal does mean that each thread gets its own copy, but they’re mutable. SharedImmutable means all threads see that instance, but it’s “frozen”. I don’t know what will happen if you have a SharedImmutable as a field in a ThreadLocal
Atomic ref would be a way to do this, but you should get a better understanding of what’s happening
1
d
It'll be frozen in each thread I think.
It might be frozen for each thread, but hard to say. Not sure the runtime pays attention to those annotations after top level (though it might)
c
How can I use the
AtomicReference
? It doesn’t seem to be in the common stdlib, and I can’t seem to find documentation on a particular artifact I need to use for native
k
In any case, you do need to dump that threadlocal if multiple threads need it
Glad you asked…
Common code, does expect/actual to jvm and native
d
@kpgalligan Have you used
kotlinx.atomicfu
?
k
Last time I checked although that complied for native, it didn’t actually work, but I haven’t looked in a bit (looking now…)
Yeah…
Only supports single threads, which defeats the purpose (for what we’re doing)
Before stately I had a fork of atomic fu working, but I figured I’d just stay out of that lane until that gets and update, and we’ll start deprecating stately features. That’s already happened to SharedImmutable and ThreadLocal. Those are available in common now
c
Finally got this working, Stately has helped greatly in using the
AtomicReference
. “Stranger Threads: Part 2” also really helped me understand this all better, in particular the sections about freezing objects and atomics. Thanks for the help, y’all!
k
Sweet! There should be a part 3 on Threading explaining how to apply in multiplatform, but busy busy with the coding