Java Thread How to - Concurrent Reads from Unmodfiable Map








Question

We would like to know how to concurrent Reads from Unmodfiable Map.

Answer

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/*from  w  ww.j  a v  a  2 s .com*/
public class Main {
  public static Map<String, String> mapGetter() {
    return MapHolder.staticMap;
  }
  public static void main(String[] arg) {
    Map<String, String> m = mapGetter();
    System.out.println("we get it: " + m);
  }
}

class MapHolder {
  static final Map<String, String> staticMap;
  static {
    Map<String, String> tempMap = new HashMap<String, String>();

    tempMap.put("key 1", "value 1");
    tempMap.put("key 2", "value 2");
    tempMap.put("key 3", "value 3");

    staticMap = Collections.unmodifiableMap(tempMap);
  }
}

The code above generates the following result.