Hello! I have a question about performance and sy...
# coroutines
d
Hello! I have a question about performance and synchronized collection. All implementation that I found for synchronized collection are using a locker that is not a mutex. Consequently, if two coroutine are trying to interact with the collection in the same time, potentially, the entire thread of one coroutine will be locked and not only the coroutine (if I understand correctly) So, my question is: Would it be more efficient to have a synchronized collection dedicated to coroutine with all methods with "suspend" keyword? If yes, I'm surprised that no one create a library to do that
s
You're right, ordinary synchronized collections won't always work well with coroutines. A special suspending collection might be an improvement, but as you noted, that doesn't seem to be a common approach. Why not? Well, coroutines already have other (better?) solutions to the same problem. In particular, we can have coroutines communicate with each other via channels. Instead of having many coroutines interact with the same mutable collection, we can make one coroutine that interacts with the collection, and have all our other coroutines interact with the first coroutine through a channel. All the tricky synchronization is handled by existing primitives, and the resulting code will generally be very efficient and easy to follow. So there's no real reason for a custom suspending collection—it wouldn't be an improvement on what we can already do.
b
another caveat is once you made this suspending collection it will 1. no longer be accessible from non-suspending code (besides
runBlocking { collection.add(..) }
) 2. not fit into existing Collection/MutableCollection/Iterable hierarchy so you will either loose all the benefits (extensions, syntax sugar) or duplicate them all with a little to zero benefit
d
Thanks for your response!