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

5 messages · Page 1 of 1 (latest)

amber snowBOT
#
Question of the Week #91

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

coarse emberBOT
#

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<>());

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
📖 Sample answer from dan1st
coarse emberBOT
#

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
#

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
#

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