RaceBase
RaceBase

Reputation: 18868

Creating Synchronized static singleton Map in Java

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

Upvotes: 0

Views: 5075

Answers (3)

Louis Wasserman
Louis Wasserman

Reputation: 198451

Collections.singletonMap returns an immutable Map with exactly one entry, not a "singleton" in the sense of "only one exists in your application." (If you use Collections.singletonMap, there's no need to synchronize it, since it's unmodifiable.)

Upvotes: 3

Narendra Pathai
Narendra Pathai

Reputation: 41995

Its better to use ConcurrentHashMap for performance reasons also, synchronizedMap will cause lock on the map instance and will reduce the performance. But in ConcurrentHashMap there is highly optimized algorithms for achieving high level of concurrency.

For an example ConcurrentHashMap has lock for each Hash Bucket and so multiple threads can even update the map.

ConcurrentHashMap is better than synchronizedMap.

Upvotes: 3

DigitalZebra
DigitalZebra

Reputation: 41583

Use ConcurrentMap if you are using Java 6+:

public class MapHolder {
    public static final ConcurrentMap<String, Object> A_MAP = new ConcurrentHashMap<String, Object>();
}

Upvotes: 3

Related Questions