Skip to main content

Is HashMap.KeySet() thread safe ?

1 reply [Last post]
Joined: 2009-01-17

Hi Friends ,

In this code
public class Test{

private final Map map= new HashMap();

public synchronized Set getAllData() {
return map.keySet();


is keyset thread safe? I believe this is more prone to concurrent modification exception as the keyset will hold the snapshot of the key and values in the memory and in the mean while if data is changed underlying by other thread then we will get concurrent modification exception.

here i have used synchronized on the method but which takes a lock on the Test Object .
Though i have synchronized the method I believe right way here to synchronize the whole map hence I feel this code is a serious problem.

Please correct me if i am wrong.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Joined: 2005-11-01

The Set returned is not thread safe.

Set does not produce a ConcurrentModificiationException but an Iterator can.
Note: you can produce a CME with just one thread so its not just a thread safety issue.

In this case you can only make the Set therad safe by;
- taking a copy of it
return new HashSet(map.keySet());

- or use a ConcurrentHashMap
private final Map map= new ConcurrentHashMap();
public Set getAllData() {
return map.keySet();