Is there a Kotlin equivalent for a Swift `Dispatch...
# announcements
d
Is there a Kotlin equivalent for a Swift
DispatchQue
? I have a
MutableMap<T,T>
and I want to make operations done to it thread safe. So far I just wrap accesses to it in:
Copy code
val lock = Any()
synchronised(lock) { map.doTheThing() }
Is this fine?
m
Locking like that is fine. But you’ll also have to lock the reads. For dispatch-like programming check out https://kotlinlang.org/docs/reference/coroutines-overview.html
d
@Marc Knaup Thanks, I am doing that too. So far I am just putting things in and getting things out. I wrap both operations with
synchronized
and the same static lock. Is that fine?
m
Yes that’s fine as long as your code is okay to be blocking. Also in case you can use Java classes and only do simple reads/writes check out https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html
n
if you want to go that route, I'd just use synchronizedMap, but the locking is pretty coarse-grained. if you need decent throughput, use a ConcurrentHashMap like Marc suggested
d
The map is not going to be accessed often.
Mostly during init of the application and a few times later.
Its for a Multiton pattern.
If that's makes it's usage more clear.