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

addamsson

07/08/2019, 12:33 PM
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

bezrukov

07/08/2019, 12:46 PM
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

addamsson

07/08/2019, 1:14 PM
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

Dominaezzz

07/08/2019, 1:46 PM
I think you either need an actor or a
Mutex
.
a

addamsson

07/08/2019, 1:57 PM
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

bdawg.io

07/08/2019, 3:50 PM
Does
.toMap()
work on
ConcurrentHashMap
? IIRC,
.toMap()
creates a new map and duplicates the contents
b

bezrukov

07/08/2019, 4:34 PM
.toMap()
is just equivalent to
LinkedHashMap(map)
, so the result may be inconsistent
b

bdawg.io

07/08/2019, 5:51 PM
Makes sense, I wasn't sure if ConcurrentHashMap has a thread-safe iterator that could be used to create the snapshot from
a

addamsson

07/09/2019, 8:48 AM
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
3 Views