Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?
like image 437
fbahr Avatar asked Jul 05 '12 18:07

fbahr


1 Answers

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)

like image 87
Peter Lawrey Avatar answered Oct 05 '22 08:10

Peter Lawrey