https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Animesh Sahu

11/18/2019, 3:34 PM
are coroutines thread safe, like should i use atomic types?
g

gildor

11/18/2019, 3:38 PM
It depends what exactly you are doing
a

Animesh Sahu

11/18/2019, 3:45 PM
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

zak.taccardi

11/18/2019, 5:23 PM
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

SrSouza

11/18/2019, 9:40 PM
Sad that Actors is not multiplataform
z

zak.taccardi

11/18/2019, 10:35 PM
Why aren't they?
You can replicate an actor with a channel that you just launch immediately and maintain a reference to it
3 Views