When multiple threads modify a shared state, it can lead to unexpected results. This problem was already discussed in the previous item, but now I want to explain it in more detail and show how to deal with it in Kotlin/JVM. By Marcin MoskaĆa.
Java also provides some collections that have support for concurrency. The most important one is ConcurrentHashMap, which is a thread-safe version of HashMap. We can safely use all its operations without worrying about conflicts. When we iterate over it, we get a snapshot of the state at the moment of iteration, therefore we’ll never get a ConcurrentModificationException exception, but this doesn’t mean that we’ll get the most recent state.
The article then will guide you through:
- The problem with threads and shared state
- Synchronization in Kotlin/JVM
- Atomic objects
- Concurrent collections
- Do not leak mutation points
Multiple threads modifying the same state can lead to conflicts, thus causing lost data, exceptions, and other unexpected behavior. We can use synchronization to protect a state from concurrent modifications. The most popular tool in Kotlin/JVM is a synchronized block with a lock. Follow the link to the full article to learn more!
[Read More]