Sobes.tech
Junior — Middle

Kas saaksid tuua näiteid kogumistruktuuridest, mis tagavad lõimede turvalisuse?

sobes.tech AI

Vastus AI-lt

In Java, there are several collections that ensure thread safety:

  • Vector — a thread-safe version of ArrayList, all methods are synchronized.
  • Hashtable — a thread-safe version of HashMap.
  • Collections from the java.util.concurrent package:
    • ConcurrentHashMap — a high-performance, thread-safe hash table.
    • CopyOnWriteArrayList — a thread-safe list, optimal for scenarios with frequent reads and rare modifications.
    • BlockingQueue and its implementations (LinkedBlockingQueue, ArrayBlockingQueue) — thread-safe queues with blocking operations.

Example of using ConcurrentHashMap:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
Integer value = map.get("key");

These structures allow safe working with collections from multiple threads without external synchronization.