說明
1、ConcurentHashMap結合了HashMap和Hashtable的優點。 HashMap不考慮同步,Hashtable考慮同步。但是Hashtable每次同步都要鎖定整個結構。
2、ConcurentHashMap鎖定的方式是稍微細粒度的。 ConcurentHashMap將hash表分成16桶(預設值),如get、put、remove等常用操作只鎖定目前需要的桶子。
實例
/** * 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中文網其他相關文章!