Week 91 — What are synchronized collections and how do they differ from regular collections?

Question of the Week #91
What are synchronized collections and how do they differ from regular collections?
5 Replies
Eric McIntyre
Eric McIntyre3mo ago
Synchronized collections allow thread-safe access to collections by locking each access and preventing concurrent accesses to the collection. It is possible to create a synchronized collection from an existing collection using the synchronizedList, synchronizedSet and synchronizedMap methods in the Collections class.
List<String> someSynchronizedList = Collections.synchronizedList(new ArrayList<>());
Set<String> someSynchronizedSet = Collections.synchronizedSet(new HashSet<>());
Map<String, String> someSynchronizedMap = Collections.synchronizedMap(new HashMap<>());
List<String> someSynchronizedList = Collections.synchronizedList(new ArrayList<>());
Set<String> someSynchronizedSet = Collections.synchronizedSet(new HashSet<>());
Map<String, String> someSynchronizedMap = Collections.synchronizedMap(new HashMap<>());
The collections returned by these methods are thread-safe meaning they will work correctly even if the objects are accessed from multiple threads. However, this property doesn't hold if the original collections are accessed:
List<String> someList = new ArrayList<>();
List<String> synchronizedView = Collections.synchronizedList(someList);//DON'T DO THIS, accessing someList destroys thread-safety
new Thread(() -> {
synchronizedView.add("Hello");
}).start();
someList.add("World");//DON'T DO THIS, UNDEFINED BEHAVIOR
synchronizedView.add(";)");//safe
List<String> someList = new ArrayList<>();
List<String> synchronizedView = Collections.synchronizedList(someList);//DON'T DO THIS, accessing someList destroys thread-safety
new Thread(() -> {
synchronizedView.add("Hello");
}).start();
someList.add("World");//DON'T DO THIS, UNDEFINED BEHAVIOR
synchronizedView.add(";)");//safe
📖 Sample answer from dan1st
Eric McIntyre
Eric McIntyre3mo ago
Synchronized collection is basically an enhanced form of collection as they are synchronised so they are threadsafe but the performance will be slower. for e.g. 2 theads are updating single value which is in synchronised block so they have to have for 1 thread process to update only then other can access.
Submission from srv2381
Eric McIntyre
Eric McIntyre3mo ago
Java's collection framework is one of the fundamental components in java application. Collections in java represent a group of objects and provides several interfaces and implementations to work with these collections. With the advent of multi-threaded programming, the need for thread-safe collections grew. It is when Synchronized Collections were added to Java’s Collection framework. Collection classes are not synchronized by default. The collection object is mutable that means once creating the object and that object is calling two threads at a time but one thread is changing the value of the object then it can be effected by another object. So, it is not thread safe. We can explicitly synchronized collection using static method java.util.Collections.synchronizedCollection(Collection<T> c)
Submission from adwaith0240
Eric McIntyre
Eric McIntyre3mo ago
Quite simply, its thread safe. Using a synchronized collection allows multiple threads to use the collection safely. It does this by instrinsic locking all is public methods.
Submission from cyanshepherd
Eric McIntyre
Eric McIntyre3mo ago
Bear in mind: "Collection" here refers to implementations of the Collection and Map interfaces, respectively. "synchronized" collections usually refer to a group of collections, where each collection that is at least partially implemented to have its API methods be safe to use in a concurrent environment. "Normal" collections assume single thread access. They count the amount of modifications made. That number is stored into a local variable and compared to the current object-local variable, before return on usually most, if not all, of it's API methods. If the numbers do not match, a ConcurrentModificationException is thrown, to signal a misuse - a single-thread specific collection was used in a multithread environment (sometimes CME can also be wrongly thrown during method in method invocation, for example: if Collection::remove was called in an Iterator loop and similar). Collections usually have both a single-thread and a multi-thread implementation. A famous example of this can be a HashMap (single-thread use), and a ConcurrentHashMap (multi-thread use). Internally, concurrent collections declare their mutable references as volatile, in order to ensure memory safety (which comes with about a x100 slower access time, due to no thread-caching). They can still be blazingly fast by using a lot of tricks, like for example ConcurrentHashMap using CAS (compare and swap) and only synchronizing it's internal bucket object (called Nodes in this case) during modifications. This allows for a much better performance, compared to for example Collections.synchronizedMap, which synchronizes the whole object during pretty much any API call, Map::get included. Thus, using Collections.synchronized(something) is undoubtebly much, much worse than using a collection intended for concurrent usage (due to, as mentioned, worse performance, possibly incorrect data being stored and read, and some API calls still not being compatible with a concurrent environment, like Iterators).
Submission from shadowofheaven
Want results from more Discord servers?
Add your server