Collections.newSetFromMap(»ConcurrentHashMap«) vs. Collections.synchronizedSet(»HashSet«)

collections, concurrency, hashset, java, thread-safety

Solution

What you may be thinking of is

Set<Type> set = Collections.newSetFromMap(new ConcurrentHashMap<Type, Boolean>());

This supports concurrent updates and reads. Its Iterator won't throw ConcurrentModicationException. where as

Set<Type> set = Collections.synchronizedSet(new HashSet<Type());

Is more light weight but only allows one thread at a time to access the set. You need to lock the set explicitly if you want to Iterator over it and you can still get a CME if you don't update it in a safe way (while iterating over it)

Problem

Apparently, there are two ways to obtain a thread-safe HashSet instance using Java’s `Collections` utility class. - Collections.newSetFromMap( ConcurrentHashMap ) - Collections.synchronizedSet( HashSet ) I ask: - How do they differ? - Which, and under what circumstances, is to be preferred over the other?

Original source