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

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

王林
Release: 2023-04-19 19:52:04
forward
1875 people have browsed it

Method 1. Use Hashtable

Map<String,Object> hashtable=new Hashtable<String,Object>();
Copy after login

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<K,V> entry = (Entry<K,V>)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;
    }
Copy after login

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());
Copy after login

The following is the JDK source code

public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
        return new SynchronizedMap<>(m);
}
private static class SynchronizedMap<K,V>
        implements Map<K,V>, Serializable {
        private static final long serialVersionUID = 1978198479659022715L;
 
        private final Map<K,V> m;     // Backing Map
        final Object      mutex;        // Object on which to synchronize
 
        SynchronizedMap(Map<K,V> m) {
            this.m = Objects.requireNonNull(m);
            mutex = this;
        }
 
        SynchronizedMap(Map<K,V> 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<? extends K, ? extends V> map) {
            synchronized (mutex) {m.putAll(map);}
        }
        public void clear() {
            synchronized (mutex) {m.clear();}
        }
        ......
    }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template