数据结构进阶(一) Java中的HashMap
Java1.8的优化关注点
怎么执行的散列化?
Treeify 的时机和要求是什么?
- 数组中的元素数据至少为64个
- 链表元素数量至少为8个。
/**
* The smallest table capacity for which bins may be treeified.
* (Otherwise the table is resized if too many nodes in a bin.)
* Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
* between resizing and treeification thresholds.
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* The bin count threshold for untreeifying a (split) bin during a
* resize operation. Should be less than TREEIFY_THRESHOLD, and at
* most 6 to mesh with shrinkage detection under removal.
*/
static final int UNTREEIFY_THRESHOLD = 6;
HashMap 和HashTable有什么区别?
多线程下 HashMap不安全,
HashTable不允许有空值。
迭代方式,HashTable使用Enumeration, HashMap使用Iterator
扩容方式不同。
HashTable继承于Dictionary, HashMap继承于AbstractMap类。
怎样让HashMap也变得线程安全
Map<Integer, Integer> map = new HashMap<>();
Map<Integer, Integer> syncronizedMap = Collections.synchronizedMap(map);
// 返回一个SynchronizedMap
// 第二种方式, 使用ConcurrentHashMap
ConcurrentHashMap<Integer, Integer> chp = new ConcurrentHashMap<>();
高并发情况下集合有哪些问题?
第一代线程安全集合类: Vector,HashTable 使用synchronized 修饰了方法;
第二代线程非安全集合类: ArrayList HashMap, 线程不安全,但性能更好。 想要安全怎么办? Collections.synchronized(list);
第三代线程安全集合类:
java.util.concurrent.*;
ConcurrentHashMap;
CopyOnWriteArrayList
CopyOnWriteArraySet 注意 不是 CopyOnWriteHashSet
底层多采用Lock锁(,