Java.Core.How can you get synchronized objects of standard collections?

When you want to make standard Java collections thread-safe, you can use synchronized wrappers provided by the Collections utility class.

Let’s go through how to get synchronized (thread-safe) versions of standard collections like List, Set, Map, and SortedMap.

✅ 1. Use Collections.synchronizedXxx() methods

Java provides built-in methods to wrap your collections:

List<T> synchronizedList     = Collections.synchronizedList(originalList);
Set<T> synchronizedSet       = Collections.synchronizedSet(originalSet);
Map<K, V> synchronizedMap    = Collections.synchronizedMap(originalMap);
SortedMap<K, V> synchronizedSortedMap = Collections.synchronizedSortedMap(originalSortedMap);

📦 Example: Synchronized List

List<String> list = new ArrayList<>();
List<String> syncList = Collections.synchronizedList(list);

// Safe to use in multithreaded code
syncList.add("apple");
syncList.add("banana");

⚠️ Important: Manual synchronization when iterating

Even though the collection is synchronized, iteration is not thread-safe by default. So when iterating over a synchronized collection, you must do:

synchronized (syncList) {
    for (String item : syncList) {
        System.out.println(item);
    }
}

Why? Because even if the methods are thread-safe, the iteration can still break if another thread modifies the collection while you’re iterating.


🛡️ Bonus: Modern alternative — java.util.concurrent package

For most serious concurrent use cases, Java recommends using concurrent collections, like:

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • ConcurrentLinkedQueue

They’re faster and more scalable than synchronized wrappers in multithreaded environments.

🧠 TL;DR

Collection TypeSynchronized Version
ListCollections.synchronizedList(list)
SetCollections.synchronizedSet(set)
MapCollections.synchronizedMap(map)
SortedMapCollections.synchronizedSortedMap(sortedMap)

📌 Don’t forget to use synchronized(collection) when iterating!

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.