说明
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?的详细内容。