Maison  >  Article  >  Java  >  Comment utiliser ConcurrentHashMap en Java ?

Comment utiliser ConcurrentHashMap en Java ?

PHPz
PHPzavant
2023-04-26 14:34:07661parcourir

Explication

1. ConcurentHashMap combine les avantages de HashMap et de Hashtable. HashMap ne prend pas en compte la synchronisation, contrairement à Hashtable. Mais Hashtable doit verrouiller toute la structure à chaque fois qu'elle est synchronisée.

2. La méthode de verrouillage ConcurentHashMap est légèrement fine. ConcurentHashMap divise la table de hachage en 16 compartiments (valeur par défaut). Les opérations courantes telles que l'obtention, le placement et la suppression verrouillent uniquement les compartiments actuellement nécessaires.

Instances

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer