Sobes.tech
Junior — Middle

Can you name and describe with an example the most common thread-safe collections in Java?

sobes.tech AI

Answer from AI

In Java, classes from the java.util.concurrent package and wrappers from Collections.synchronizedXXX() are most commonly used for working with thread-safe collections. Here are the most common:

  1. ConcurrentHashMap — a thread-safe version of HashMap that allows multiple threads to read and write without locking the entire map. It uses segmentation to improve performance.
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
int value = map.get("key");
  1. CopyOnWriteArrayList — a thread-safe list that creates a copy of the internal array upon modifications (adding, removing). Good for scenarios with frequent reads and infrequent modifications.
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("element");
String elem = list.get(0);
  1. BlockingQueue (e.g., LinkedBlockingQueue) — a thread-safe queue with blocking operations, useful for organizing task queues between threads.
BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("task");
String task = queue.take();
  1. Collections.synchronizedList() — a wrapper around a regular list that synchronizes all methods for thread safety.
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
syncList.add("item");

These collections help avoid issues with concurrent access without the need to manually write synchronization.

Can you name and describe with an example the most… - sobes.tech