Reputation: 18868
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
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
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
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