Is it possible to implement a concurrent hash map purely in Kotlin (without Java dependency)? I am new to Kotlin and it looks like there is no obvious API available in kotlin.collections.
There is no convenient concurrent hash map implemented purely in Kotlin, at least not built into the platform. Someone might have done it in open source, but it would be out of StackOverflow's scope to look for or suggest it. (That said, I wouldn't bet on anyone having done it really correctly.)
True concurrent hash tables are extremely difficult to build and I would not recommend just about anyone make the attempt.
In general, almost certainly the most appropriate thing to do -- especially in the Kotlin multiplatform space -- is to simply wrap a normal MutableMap with a simple mutex (possibly a standard coroutine Mutex). That should generally perform well enough for the environments KMP is likely to be used in.
Try touchlab/Stately. Here's a list of the collections with added thread-safety:
ConcurrentMutableList.kt
ConcurrentMutableMap.kt
ConcurrentMutableSet.kt
You can probably convert the source without too many issues. It's freely available, here for example. The concurrency model of Kotlin multiplatform (which I'm guessing is your goal, there's no point in reimplementing it if you only target the JVM) is a bit different than the one Java uses, there are no locks for example. But there's no reason why that would prevent it.
The following resources might also help you with the implementation:
You can try:
val emitters: ConcurrentMap<String, Any> = ConcurrentHashMap()
// get
val obj: Any = emitters[email]
// put:
emitters[email] = this
// delete
emitters.remove(email)
Such way, u don't need to add any library to your project
ConcurrentHashMap
you refer to here requires a Java dependency. –
Transform © 2022 - 2024 — McMap. All rights reserved.