Home>Article>Java> What are the ways to implement thread safety for Map in Java?

What are the ways to implement thread safety for Map in Java?

王林
王林 forward
2023-04-19 19:52:04 1655browse

Method 1. Use Hashtable

Map hashtable=new Hashtable();

This is the first thing everyone thinks of, so why is it thread-safe? Then take a look at its source code. We can see that our commonly used methods such as put, get, and containsKey are all synchronous, so it is thread-safe.

public synchronized boolean containsKey(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return true; } } return false; } public synchronized V get(Object key) { Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; for (Entry e = tab[index] ; e != null ; e = e.next) { if ((e.hash == hash) && e.key.equals(key)) { return (V)e.value; } } return null; } public synchronized V put(K key, V value) { // Make sure the value is not null if (value == null) { throw new NullPointerException(); } // Makes sure the key is not already in the hashtable. Entry tab[] = table; int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length; @SuppressWarnings("unchecked") Entry entry = (Entry)tab[index]; for(; entry != null ; entry = entry.next) { if ((entry.hash == hash) && entry.key.equals(key)) { V old = entry.value; entry.value = value; return old; } } addEntry(hash, key, value, index); return null; }

The implementation principle is to add, delete, modify, and check. The synchronized lock mechanism is used. In a multi-threaded environment, whether it is reading data or modifying data, only one thread can execute the synchronize method at the same time because the entire table is locked. Therefore, the more threads there are, the more intense the competition for the map and the lower the efficiency. It is not recommended.

Method 2. Use Collections.synchronizedMap(new Hashtable())

The implementation principle is to use the static method in the tool class to package the incoming Hashtable into a synchronized one, that is, in The synchronized mechanism is added to the method of adding, deleting, modifying, and checking. Its implementation is similar to that of Hashtable, and its efficiency is similar. It is not recommended to use.

Map map = Collections.synchronizedMap(new Hashtable());

The following is the JDK source code

public static  Map synchronizedMap(Map m) { return new SynchronizedMap<>(m); } private static class SynchronizedMap implements Map, Serializable { private static final long serialVersionUID = 1978198479659022715L; private final Map m; // Backing Map final Object mutex; // Object on which to synchronize SynchronizedMap(Map m) { this.m = Objects.requireNonNull(m); mutex = this; } SynchronizedMap(Map m, Object mutex) { this.m = m; this.mutex = mutex; } public int size() { synchronized (mutex) {return m.size();} } public boolean isEmpty() { synchronized (mutex) {return m.isEmpty();} } public boolean containsKey(Object key) { synchronized (mutex) {return m.containsKey(key);} } public boolean containsValue(Object value) { synchronized (mutex) {return m.containsValue(value);} } public V get(Object key) { synchronized (mutex) {return m.get(key);} } public V put(K key, V value) { synchronized (mutex) {return m.put(key, value);} } public V remove(Object key) { synchronized (mutex) {return m.remove(key);} } public void putAll(Map map) { synchronized (mutex) {m.putAll(map);} } public void clear() { synchronized (mutex) {m.clear();} } ...... }

Method 3. Use ConcurrentHashMap

The implementation principle is that Hashtable locks the entire table, while ConcurrentHashMap segments the table , initially divided into 16 segments, each segment has a lock. When multiple threads access different segments, because the locks obtained are different, they can be accessed in parallel. The efficiency is much higher than Hashtable, so it is recommended to use it.

The above is the detailed content of What are the ways to implement thread safety for Map in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete