short version: Is there a coroutine equivalent to ConcurrentHashMap?
long version: What I'm using now is manual locking of
getOrPut
, so
Copy code
data object ProxyMode {
private val certificateCache: MutableMap<String, BCECPublicKey> = mutableMapOf()
private val lock = Mutex()
...
suspend fun getRequest(...): Pair<HttpClient, RequestData> {
...
val serverEncPublicKey: BCECPublicKey = lock.withLock { certificateCache.getOrPut(host) {
loadCertificate("https://$host/Certificate").bcecPublicKey
} }
...
}
}
but I wonder if a way exists where the locking is part of the collection class but which still locks the coroutine and not the thread.
a
Aleksei Tirman [JB]
03/12/2024, 1:48 PM
I suggest asking this question in the #coroutines channel.
c
CLOVIS
03/12/2024, 2:36 PM
No, there isn't.
Because many functionalities of collections are provided by extension functions, they can never be made truly atomic. For example, even if you use ConcurrentHashMap, a
getOrPut
call won't be atomic.
s
Stephan Schröder
03/12/2024, 10:00 PM
you're right,
getOrPut
wouldn't be atomic but
computeIfAbsent
would, but unfortunately that one would block the thread and not the coroutine 🤷♂️