Home > Java > javaTutorial > How to use ConcurrentHashMap in Java?

How to use ConcurrentHashMap in Java?

PHPz
Release: 2023-04-26 14:34:07
forward
754 people have browsed it

Explanation

1. ConcurentHashMap combines the advantages of HashMap and Hashtable. HashMap does not consider synchronization, Hashtable does. But Hashtable must lock the entire structure every time it is synchronized.

2. ConcurentHashMap locking method is slightly fine-grained. ConcurentHashMap divides the hash table into 16 buckets (default value). Common operations such as get, put, and remove only lock the buckets currently needed.

Example

/**
     * Creates a new, empty map with the default initial table size (16).
     */
    public ConcurrentHashMap() {
    }
 
    /**
     * Creates a new, empty map with an initial table size
     * accommodating the specified number of elements without the need
     * to dynamically resize.
     *
     * @param initialCapacity The implementation performs internal
     * sizing to accommodate this many elements.
     * @throws IllegalArgumentException if the initial capacity of
     * elements is negative
     */
    public ConcurrentHashMap(int initialCapacity) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException();
        int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                   MAXIMUM_CAPACITY :
                   tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
        this.sizeCtl = cap;
    }
 
    /**
     * Creates a new map with the same mappings as the given map.
     *
     * @param m the map
     */
    public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
        this.sizeCtl = DEFAULT_CAPACITY;
        putAll(m);
    }
Copy after login

The above is the detailed content of How to use ConcurrentHashMap 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