What is the reason behind `objects` being frozen -...
# announcements
a
What is the reason behind
objects
being frozen - technical limitation or a language concept? What us then the alternative of keeping the global modifiable list of, say, users in the app?
m
Frozen objects are immutable, immutable objects are thread-safe, thread-safe objects remove multi-threading bugs
a
I see the logic here, but how do I implement [mutable] singleton multithreaded component in Kotlin?
Notify me if this helps, I'm also interested in solution but I don't have time to allocate to this right now
o
What's preventing you from declaring the fields inside an object as
var
, or setting a mutable object (like a
MutableList
) as a field?
a
Hm.. just checked - I have my mutable list declared inside the object like
private val fetchers: ArrayList<DataSourceFetcher> = ArrayList()
. Will try the same using `var`and report.
c
Once an object is frozen, all its children objects are also frozen. The only way to have mutable properties in an
object
for mutable singletons is to use
AtomicReference
or other atomic data structures. I was fighting this a while ago and that really is the only route, unfortunately
o
Oh, is this a KotlinJS or Android thing? Because JVM objects are just singletons. I just tested out some code with a mutableList field in an object.
i
@alan.kleiman This is a Kotlin/Native memory model restriction
o
Ah, I see, thanks.
a
Any ideas why
AtomicReference
is not available for me? Kotlin '1.3.30'
m
Is it available on Native only?
a
According to documentation - it should be in both Common and Native.
m
There's atomicfu that should have multiplaform atomic ops https://github.com/Kotlin/kotlinx.atomicfu
Not sure if that is the right way to go. Can somebody help? @ilya.gorbunov
a
@Casey Brooks
Once an object is frozen, all its children objects are also frozen.
Is there any option to distinguish between real children (owned) and referenced objects? Currently if I pass some object in constructor to the frozen object, that one is also get frozen which is not what I want.