I have implemented a sleep sort algorithm using co...
# coroutines
i
I have implemented a sleep sort algorithm using coroutines (don’t ask me why🤣) and now Vasya asks me if this implementation is thread-safe? And now I really wonder if it is thread-save to access
sortedList
like this? https://twitter.com/igorwojda/status/1255416485293502465
a
(JVM) the mutableListOf returns a LinkedHashSet, which is not concurrent-modification safe (although it seems unlikely you’d hit that in this example, with the writes guaranteed to be 1sec apart)
👍 1
o
if you use a single-threaded dispatcher like
Dispatchers.Main
(if you have it) or
Executors.newSingleThreadExecutor().asDispatcher()
, you could actually make this thread safe
👍 1
e
Also, don’t use GlobalScope if you can avoid it! Errors won’t be thrown properly
o
err, rather, not "thread safe" but it wouldn't be cross-thread anymore
d
Cool sort though. 😁
o
and yes, the solution to not use GlobalScope here is to do:
Copy code
coroutineScope {
  for (elm in list) {
    launch(properDispatcher) {
      delay(1000L * elm)
      sortedList.add(elm)
    }
  }
}
e
Instead, use the
coroutineScope()
builder and either a mutex or a channel to control access to the shared list lol
Here’s how you can do it with a channel:
d
Should actually be
launch
.
o
ah, yes
d
Should also leave the dispatcher to be inherited from context.
o
well, I was assuming a patch with the new dispatcher, so you'd either have to wrap the
coroutineScope
or the loop with
withContext
in that case
e
The above snippet is thread-safe due to only the receiver coroutine mutating the list 🙂
👍 1
d
Might as well go all the way and do
channelFlow { ... }.toList()
. 😁
👍 2
e
That too lol
k
Ideally, you'd have a way shorter delay, and add a insertion sort final step