I have a question about coroutines. What is the fa...
# coroutines
a
I have a question about coroutines. What is the fastest way to restrict access to a shared resource? I've checked this article: https://kotlinlang.org/docs/reference/coroutines/shared-mutable-state-and-concurrency.html but it doesn't detail the performance characteristics of the solutions
What I have is a
Map
which I want to both write and access concurrently so I need to maintain a consistent state of it
Should I use an
actor
as explained in the last example?
b
performance (and better solution) highly depends on your use case
Most likely ConcurrentHashMap is enough for you
e.g. quote from page you mentioned:
Thread-safe data structures
This is the fastest solution for this particular problem. It works for plain counters, collections, queues and other standard data structures and basic operations on them. However, it does not easily scale to complex state or to complex operations that do not have ready-to-use thread-safe implementations.
a
the problem is that
ConcurrentHashMap
doesn't support consistent snapshots
I tried that way
😞
my code is also common Kotlin code so I can't use Java things
my use case is that I want to create a snapshot of my
Map
and return it to some external api
but with
ConcurrentHashMap
this is not possible 😞
d
I think you either need an actor or a
Mutex
.
a
i tried all the examples
and the coarse grained version was the fastest by far
around ~30ms compared to around ~300ms
the actor variant was the slowest
b
Does
.toMap()
work on
ConcurrentHashMap
? IIRC,
.toMap()
creates a new map and duplicates the contents
b
.toMap()
is just equivalent to
LinkedHashMap(map)
, so the result may be inconsistent
b
Makes sense, I wasn't sure if ConcurrentHashMap has a thread-safe iterator that could be used to create the snapshot from
a
no it is in the docs that the iterator is thread safe but not consistent 😞
so i either need persistent data structures or one of the solutions in the article