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.
Asked
Active
Viewed 3,122 times
2 Answers
0
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:

Nicolas
- 6,611
- 3
- 29
- 73
-
Yes, the goal is Kotlin multiplatform where commonMain does not have access to Java packages. These resources have lot of other multi-threading related concepts. I just need a HashMap where multiple threads can safely insert/remove data. Could you please tell how exactly I can implement this? – Raj Kukadia Nov 03 '20 at 03:03
-
I don't know a lot unfortunately, I haven't even actually used multiplatform. But does it really make sense to have the same implementation for all platforms? JS isn't multithreaded, so a regular map would work just fine. For JVM you already have an implementation. And for native you can do you best to translate the JVM implementation with the resources above. I suggest you also try asking on [Kotlin Discussions](https://discuss.kotlinlang.org/), you'll certainly get better answers. – Nicolas Nov 03 '20 at 12:57
-1
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

Dmitry Kaltovich
- 2,046
- 19
- 21