are coroutines thread safe, like should i use atom...
# coroutines
a
are coroutines thread safe, like should i use atomic types?
g
It depends what exactly you are doing
a
I'm implementing/typing to achieve lateinit vals using delegation, since the call is blocking i dont want to block thread while instantiating object, using IO dispatcher to set the val, and ensuring no override can be done.
Copy code
private val value= AtomicReference<T>()
if (!value.compareAndSet(null, value)) {...}
vs
Copy code
private var value: T? = null
if (this.value != null) {...}
in case of dispatching to io pool, should atomic references be used
Ohh wow lol https://discuss.kotlinlang.org/t/idiomatic-way-for-asynchronous-construction/14560 fake constructors are great xd, i would just do all async work in there before initializing the object
z
a coroutine is thread safe
but if you access state from outside that coroutine and that state isn’t thread safe, then you will have a race condition
you can think of thread safety as something being thread safe based on the context it’s being written to and read from
AtomicBoolean
is thread safe by itself, but use it in an object that isn’t thread safe and your
Boolean
is no longer thread safe
coroutines are no different
but using a coroutine + message passing is an awesome way to achieve thread safety. https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html#actors
s
Sad that Actors is not multiplataform
z
Why aren't they?
You can replicate an actor with a channel that you just launch immediately and maintain a reference to it