HashMap은 HashTable과는 다르게 Thread-safe하지 않다.
그래서 put이나 get을 사용할 때 명시적으로 동기화를 시켜주어야 한다.
하지만 Collections.SynchronizedMap()이라는 메소드로 thread-safe하게 만들 수 있다.

이 경우에,
Simple operation (put, get) 등은 synchronized로 감싸주지 않아도 된다.
하지만 iterator를 사용해서 탐색을 할 경우에는 따로 명시적으로
Synchronized를 써주어야 한단다.

Map m = Collections.synchronizedMap(new HashMap());
      ...
  Set s = m.keySet();  // Needn't be in synchronized block
      ...
  synchronized(m) {  // Synchronizing on m, not s!
      Iterator i = s.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)



+ Recent posts