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

How to use ConcurrentHashMap in Java?

PHPz
PHPzforward
2023-04-26 14:34:07663browse

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);
    }

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!

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