0

I have enough knowledge on creating Synchronized static objects. However for a Map (Collection) in Java,

I found default implementations in Java individually (one for Synchronized list and one for for Singleton map).

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#singletonMap(K, V)

I am thinking of getting the desired result by following implementation

Map<K,V> initMap = new HashMap<K,V>(); 
Map<K,V> syncSingMap = Collections.synchronizedMap(Collection.singletonMap(initMap));

Am i making right sense? Because documentation at oracle shows some warning on this

It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:

 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());
 }

 Failure to follow this advice may result in non-deterministic behavior

How about using ConcurrentMap over this.

Requriement: static synchronized singleton map which will be used by tons of threads for some processing operations

UPDATE

After going through few articles, found that ConcurrentMap is much preferable than HashMap in multi-thread environment http://java.dzone.com/articles/java-7-hashmap-vs

4

3 に答える 3

3

Collections.singletonMapMap「アプリケーションに 1 つしか存在しない」という意味での「シングルトン」ではなく、1 つのエントリを持つ不変を返します。( を使用する場合はCollections.singletonMap、変更できないため、同期する必要はありません。)

于 2012-12-06T16:37:24.693 に答える
2

Java 6+ を使用している場合は、ConcurrentMap を使用します。

public class MapHolder {
    public static final ConcurrentMap<String, Object> A_MAP = new ConcurrentHashMap<String, Object>();
}
于 2012-12-06T04:24:39.857 に答える
2

パフォーマンスConcurrentHashMap上の理由からも使用することをお勧めしますが、マップ インスタンスで発生し、パフォーマンスが低下します。しかし、高レベルの並行性を達成するために高度に最適化されたアルゴリズムがあります。synchronizedMaplockConcurrentHashMap

たとえば、ConcurrentHashMap はハッシュ バケットごとにロックを持っているため、複数のスレッドがマップを更新することさえできます。

ConcurrentHashMapよりも優れていsynchronizedMapます。

于 2012-12-06T04:30:20.460 に答える