>  기사  >  Java  >  Java에서 ConcurrentHashMap을 사용하는 방법은 무엇입니까?

Java에서 ConcurrentHashMap을 사용하는 방법은 무엇입니까?

PHPz
PHPz앞으로
2023-04-26 14:34:07661검색

설명

1. ConcurentHashMap은 HashMap과 Hashtable의 장점을 결합합니다. HashMap은 동기화를 고려하지 않지만 Hashtable은 고려합니다. 하지만 Hashtable은 동기화될 때마다 전체 구조를 잠가야 합니다.

2. ConcurentHashMap 잠금 방법은 약간 세분화되어 있습니다. ConcurentHashMap은 해시 테이블을 16개의 버킷(기본값)으로 나눕니다. 가져오기, 넣기, 제거 등의 일반적인 작업은 현재 필요한 버킷만 잠급니다.

인스턴스

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

위 내용은 Java에서 ConcurrentHashMap을 사용하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제