Is it possible to mutate a singleton instance from...
# kotlin-native
s
Is it possible to mutate a singleton instance from a background thread via
Worker.execute
with
TransferMode.SAFE
? Basically I want to keep a global cache as a singleton instance and have the background workers able to add things to the cache. But I think that may violate mutable XOR global.
j
You should be able to use AtomicReference or DetachedObjectGraph
Or perform mutation on callback
s
hmm good point on mutating on callback. My use case is a bit more complicated so that alone won’t work but you gave me an idea of what I could do as a work around
b
you can update a reference that looks like this:
Copy code
@SharedImmutable
val someRef = AtomicReference<SomObject?>(null)
then
someRef.value = newValue.freeze()
(has to be frozen)
s
wouldn’t that mean i can no longer mutate
someRef.value
?
j
Yes you'd need to copy and replace with a different object
I think
DetachedObjectGraph
should allow you to transfer ownership and mutate
s
The thing is I will have many threads running concurrently at any given time and all will need to update the cache. Transferring seems tricky in that scenario
b
you won't be able to mutate the thing you stored in
someRef.value
anymore, correct
j
KN is designed explicitly to prevent multiple threads from updating shared mutate state
s
I know, but in some cases it is useful or even necessary
j
You may need to abstract that logic and implement on each platform