简体   繁体   中英

How to change HashMap as Synchoronized

Is it possible to change HashMap as Synchronized. If so, Please let me know how to change it.

For synchronizing a HashMap,you can use

Collections.synchronizedMap(<your hashmap reference>) 

which will return a synchronized map for you, which is thread-safe.

ConcurrentHashMap is one of the synchronized implementations.

As per javadoc

A hash table supporting full concurrency of retrievals and adjustable expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization detail

使用Collections.synchronizedMap(new HashMap());

Collections.synchronizedMap(map);

Returns a synchronized (thread-safe) map backed by the specified map. In order to guarantee serial access, it is critical that all access to the backing map is accomplished through the returned map.

Doc: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collections.html#synchronizedMap%28java.util.Map%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM