Sobes.tech
Junior — Middle

Milliseid meetodeid ja tehnoloogiaid saab kasutada andmete salvestamiseks vahemälus mitme niidiga tingimustes?

sobes.tech AI

Vastus AI-lt

In multi-threaded conditions, the following methods and technologies are used for safe data storage in cache:

  • Access synchronization: using keywords synchronized (Java/Kotlin) or locks (Lock) to prevent simultaneous data modification.
  • Concurrent collections: for example, ConcurrentHashMap for thread-safe storage of key-value pairs.
  • Immutable objects: using immutable objects to avoid issues with data changes from different threads.
  • Atomic variables: classes from the java.util.concurrent.atomic package for atomic operations.
  • Using caching libraries: such as Guava Cache or Caffeine, which already implement thread-safe cache.

Example using ConcurrentHashMap:

val cache = ConcurrentHashMap<String, String>()

fun putValue(key: String, value: String) {
    cache[key] = value
}

fun getValue(key: String): String? {
    return cache[key]
}

This approach ensures the correct operation of the cache when accessed from multiple threads simultaneously.