Thursday, August 9, 2012

An unsafe LinkedHashMap

I recently came across a case where a ConcurrentModificationException was thrown while iterating through a LinkedHashMap's key set where the only method call made on the Map was get.

Here's a demonstration:
import java.util.*;

public class LinkedHashMapExample {
 private static Map<String, Integer> m;

 public static void main(String[] args) {
  m = new LinkedHashMap<String, Integer>(16, 0.75f, true);
  m.put("first", 1);
  m.put("second", 2);
  m.put("third", 3);
  Iterator<String> i = m.keySet().iterator();
From the API:
A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.
So be wary when you're receiving a Map from a source which doesn't specify the Map's implementation or in the case of a LinkedHashMap whether it's ordered by access.

No comments:

Post a Comment