一、概述

容器主要包括 Collection 和 Map 两种,Collection 存储着对象的集合,而 Map 存储着键值对(两个对象)的映射表。

Collection

1.png

1.Set

  • TreeSet:基于红黑树实现,支持有序性操作,例如根据一个范围查找元素的操作。但是查找效率不如 HashSet,HashSet 查找的时间复杂度为 O(1),TreeSet 则为 O(logN)。
  • HashSet:基于哈希表实现,支持快速查找,但不支持有序性操作。并且失去了元素的插入顺序信息,也就是说使用 Iterator 遍历 HashSet 得到的结果是不确定的。HashSet集合初始化容量16。扩容:扩容之后是原容量的2倍。
  • LinkedHashSet:具有 HashSet 的查找效率,并且内部使用双向链表维护元素的插入顺序。

    2. List

  • ArrayList:基于动态数组实现,支持随机访问。初始化容量是10,扩容到原容量的1.5倍。

  • Vector:和 ArrayList 类似,但它是线程安全的。
  • LinkedList:基于双向链表实现,只能顺序访问,但是可以快速地在链表中间插入和删除元素。不仅如此,LinkedList 还可以用作栈、队列和双向队列。

    3. Queue

  • LinkedList:可以用它来实现双向队列。

  • PriorityQueue:基于堆结构实现,可以用它来实现优先队列。

    Map

    2.png

  • TreeMap:基于红黑树实现。

  • HashMap:基于哈希表实现。
  • HashTable:和 HashMap 类似,但它是线程安全的,这意味着同一时刻多个线程同时写入 HashTable 不会导致数据不一致。它是遗留类,不应该去使用它,而是使用 ConcurrentHashMap 来支持线程安全,ConcurrentHashMap 的效率会更高,因为 ConcurrentHashMap 引入了分段锁。

HashTable集合初始化容量11 扩容是: 原容量*2+1

  • LinkedHashMap:使用双向链表来维护元素的顺序,顺序为插入顺序或者最近最少使用(LRU)顺序。

    二、容器中的设计模式

    迭代器模式

    1.png

Collection 继承了 Iterable 接口,其中的 iterator() 方法能够产生一个 Iterator 对象,通过这个对象就可以迭代遍历 Collection 中的元素。
从 JDK 1.5 之后可以使用 foreach 方法来遍历实现了 Iterable 接口的聚合对象。

  1. List<String> list = new ArrayList<>();
  2. list.add("a");
  3. list.add("b");
  4. //增强for循环
  5. for (String item : list) {
  6. System.out.println(item);
  7. }

迭代器

  1. Iterator iterator = list.iterator();
  2. while(iterator.hasNext()){
  3. Object obj = iterator.next();
  4. System.out.println(obj);
  5. }

适配器模式

java.util.Arrays#asList() 可以把数组类型转换为 List 类型。

  1. @SafeVarargs
  2. public static <T> List<T> asList(T... a)

应该注意的是 asList() 的参数为泛型的变长参数,不能使用基本类型数组作为参数,只能使用相应的包装类型数组。

  1. Integer[] arr = {1, 2, 3};
  2. List list = Arrays.asList(arr);

也可以使用以下方式调用 asList():

  1. List list = Arrays.asList(1, 2, 3);

三、contains,remove方法解析

深入理解contains方法

contains方法调用了equals方法进行比对。
因为String类重写了equals方法,如果是 User s1 = new User(“abc”),则结果是false。(必须重写equals方法)
image.pngimage.png

深入理解remove方法

调用了equals方法
image.png

四、源码分析

如果没有特别说明,以下源码分析基于 JDK 1.8。
在 IDEA 中 double shift 调出 Search EveryWhere,查找源码文件,找到之后就可以阅读源码。

ArrayList

1.概述

因为 ArrayList 是基于数组实现的,所以支持快速随机访问。RandomAccess 接口标识着该类支持快速随机访问。

  1. public class ArrayList<E> extends AbstractList<E>
  2. implements List<E>, RandomAccess, Cloneable, java.io.Serializable

数组的默认大小为 10。

  1. private static final int DEFAULT_CAPACITY = 10;

3.png

2.扩容

添加元素时使用 ensureCapacityInternal() 方法来保证容量足够,如果不够时,需要使用 grow() 方法进行扩容,新容量的大小为 oldCapacity + (oldCapacity >> 1),即 oldCapacity+oldCapacity/2。其中 oldCapacity >> 1 需要取整,所以新容量大约是旧容量的 1.5 倍左右。(oldCapacity 为偶数就是 1.5 倍,为奇数就是 1.5 倍-0.5)
扩容操作需要调用 Arrays.copyOf() 把原数组整个复制到新数组中,这个操作代价很高,因此最好在创建 ArrayList 对象时就指定大概的容量大小,减少扩容操作的次数。
无参构造:
当创建ArrayLlist对象时,如果使用的是无参构造器,则初始elementData容量为0,第1次添加,则扩容elementData为10,如需要再次扩容,则扩容elementData为1.5倍。
有参构造:
如果使用的是指定大小的构造器,则初始elementData容量为指定大小,如果需要扩容,则直接扩容elementData为1.5倍。

  1. //假设初始化大小为8,这里分析第9个元素
  2. public boolean add(E e) { // e: 9
  3. ensureCapacityInternal(size + 1); // Increments modCount!! size:8
  4. elementData[size++] = e;
  5. return true;
  6. }
  7. private void ensureCapacityInternal(int minCapacity) { // minCapacity: 9
  8. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  9. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  10. }
  11. ensureExplicitCapacity(minCapacity);
  12. }
  13. private void ensureExplicitCapacity(int minCapacity) { //minCapacity:9
  14. modCount++;
  15. // overflow-conscious code
  16. // 9 8
  17. if (minCapacity - elementData.length > 0)
  18. grow(minCapacity);
  19. }
  20. private void grow(int minCapacity) { // minCapacity:9
  21. // overflow-conscious code
  22. int oldCapacity = elementData.length;
  23. // 12 8 8/2
  24. int newCapacity = oldCapacity + (oldCapacity >> 1);
  25. // 12 8
  26. if (newCapacity - minCapacity < 0)
  27. newCapacity = minCapacity;
  28. //注意:因为还没有到最大值,所以不走
  29. if (newCapacity - MAX_ARRAY_SIZE > 0)
  30. newCapacity = hugeCapacity(minCapacity);
  31. // minCapacity is usually close to size, so this is a win:
  32. elementData = Arrays.copyOf(elementData, newCapacity);
  33. // {1 2 3 4 5 6 7 8 9 null null null}
  34. }

3.删除元素

需要调用 System.arraycopy() 将 index+1 后面的元素都复制到 index 位置上,该操作的时间复杂度为 O(N),可以看到 ArrayList 删除元素的代价是非常高的。

  1. public E remove(int index) {
  2. rangeCheck(index);
  3. modCount++;
  4. E oldValue = elementData(index);
  5. int numMoved = size - index - 1;
  6. if (numMoved > 0)
  7. System.arraycopy(elementData, index+1, elementData, index, numMoved);
  8. elementData[--size] = null; // clear to let GC do its work
  9. return oldValue;
  10. }

4.序列化

ArrayList 基于数组实现,并且具有动态扩容特性,因此保存元素的数组不一定都会被使用,那么就没必要全部进行序列化。
保存元素的数组 elementData 使用 transient 修饰,该关键字声明数组默认不会被序列化。

  1. transient Object[] elementData; // non-private to simplify nested class access

ArrayList 实现了 writeObject() 和 readObject() 来控制只序列化数组中有元素填充那部分内容。

  1. private void readObject(java.io.ObjectInputStream s)
  2. throws java.io.IOException, ClassNotFoundException {
  3. elementData = EMPTY_ELEMENTDATA;
  4. // Read in size, and any hidden stuff
  5. s.defaultReadObject();
  6. // Read in capacity
  7. s.readInt(); // ignored
  8. if (size > 0) {
  9. // be like clone(), allocate array based upon size not capacity
  10. ensureCapacityInternal(size);
  11. Object[] a = elementData;
  12. // Read in all elements in the proper order.
  13. for (int i=0; i<size; i++) {
  14. a[i] = s.readObject();
  15. }
  16. }
  17. }
  1. rivate void writeObject(java.io.ObjectOutputStream s)
  2. throws java.io.IOException{
  3. // Write out element count, and any hidden stuff
  4. int expectedModCount = modCount;
  5. s.defaultWriteObject();
  6. // Write out size as capacity for behavioural compatibility with clone()
  7. s.writeInt(size);
  8. // Write out all elements in the proper order.
  9. for (int i=0; i<size; i++) {
  10. s.writeObject(elementData[i]);
  11. }
  12. if (modCount != expectedModCount) {
  13. throw new ConcurrentModificationException();
  14. }
  15. }

序列化时需要使用 ObjectOutputStream 的 writeObject() 将对象转换为字节流并输出。而 writeObject() 方法在传入的对象存在 writeObject() 的时候会去反射调用该对象的 writeObject() 来实现序列化。反序列化使用的是 ObjectInputStream 的 readObject() 方法,原理类似。

  1. ArrayList list = new ArrayList();
  2. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
  3. oos.writeObject(list);

5.Fail-Fast

modCount 用来记录 ArrayList 结构发生变化的次数。结构发生变化是指添加或者删除至少一个元素的所有操作,或者是调整内部数组的大小,仅仅只是设置元素的值不算结构发生变化。
在进行序列化或者迭代等操作时,需要比较操作前后 modCount 是否改变,如果改变了需要抛出 ConcurrentModificationException。代码参考上节序列化中的 writeObject() 方法。

Vector

1.同步

它的实现与 ArrayList 类似,但是使用了 synchronized 进行同步。

  1. public synchronized boolean add(E e) {
  2. modCount++;
  3. ensureCapacityHelper(elementCount + 1);
  4. elementData[elementCount++] = e;
  5. return true;
  6. }
  7. public synchronized E get(int index) {
  8. if (index >= elementCount)
  9. throw new ArrayIndexOutOfBoundsException(index);
  10. return elementData(index);
  11. }

2.扩容

Vector 的构造函数可以传入 capacityIncrement 参数,它的作用是在扩容时使容量 capacity 增长 capacityIncrement。如果这个参数的值小于等于 0,扩容时每次都令 capacity 为原来的两倍。

  1. public Vector(int initialCapacity, int capacityIncrement) {
  2. super();
  3. if (initialCapacity < 0)
  4. throw new IllegalArgumentException("Illegal Capacity: "+
  5. initialCapacity);
  6. this.elementData = new Object[initialCapacity];
  7. this.capacityIncrement = capacityIncrement;
  8. }
  1. //假设从第11个开始
  2. private void grow(int minCapacity) { //minCapacity: 11
  3. // overflow-conscious code
  4. // 10 10
  5. int oldCapacity = elementData.length;
  6. // 20 10 0
  7. int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
  8. capacityIncrement : oldCapacity);
  9. // 20 11
  10. if (newCapacity - minCapacity < 0)
  11. newCapacity = minCapacity;
  12. //没有超过最大值 不走
  13. if (newCapacity - MAX_ARRAY_SIZE > 0)
  14. newCapacity = hugeCapacity(minCapacity);
  15. elementData = Arrays.copyOf(elementData, newCapacity);
  16. }

调用没有 capacityIncrement 的构造函数时,capacityIncrement 值被设置为 0,也就是说默认情况下 Vector 每次扩容时容量都会翻倍。

  1. public Vector(int initialCapacity) {
  2. this(initialCapacity, 0);
  3. }
  4. public Vector() {
  5. this(10);
  6. }

3.与 ArrayList的比较

  • Vector 是同步的,因此开销就比 ArrayList 要大,访问速度更慢。最好使用 ArrayList 而不是 Vector,因为同步操作完全可以由程序员自己来控制;
  • Vector 每次扩容请求其大小的 2 倍(也可以通过构造函数设置增长的容量),而 ArrayList 是 1.5 倍。

4.替代方案

可以使用 Collections.synchronizedList(); 得到一个线程安全的 ArrayList。

  1. List<String> list = new ArrayList<>();
  2. List<String> synList = Collections.synchronizedList(list);

也可以使用 concurrent 并发包下的 CopyOnWriteArrayList 类。

  1. List<String> list = new CopyOnWriteArrayList<>();

CopyOnWriteArrayList

1. 读写分离

写操作在一个复制的数组上进行,读操作还是在原始数组中进行,读写分离,互不影响。
写操作需要加锁,防止并发写入时导致写入数据丢失。
写操作结束之后需要把原始数组指向新的复制数组。

  1. public boolean add(E e) {
  2. final ReentrantLock lock = this.lock;
  3. lock.lock();
  4. try {
  5. Object[] elements = getArray();
  6. int len = elements.length;
  7. Object[] newElements = Arrays.copyOf(elements, len + 1);
  8. newElements[len] = e;
  9. setArray(newElements);
  10. return true;
  11. } finally {
  12. lock.unlock();
  13. }
  14. }
  15. final void setArray(Object[] a) {
  16. array = a;
  17. }
  1. @SuppressWarnings("unchecked")
  2. private E get(Object[] a, int index) {
  3. return (E) a[index];
  4. }

2. 适用场景

CopyOnWriteArrayList 在写操作的同时允许读操作,大大提高了读操作的性能,因此很适合读多写少的应用场景。
但是 CopyOnWriteArrayList 有其缺陷:

  • 内存占用:在写操作时需要复制一个新的数组,使得内存占用为原来的两倍左右;
  • 数据不一致:读操作不能读取实时性的数据,因为部分写操作的数据还未同步到读数组中。

所以 CopyOnWriteArrayList 不适合内存敏感以及对实时性要求很高的场景。

LinkedList

1. 概览

基于双向链表实现,使用 Node 存储链表节点信息。

  1. private static class Node<E> {
  2. E item;
  3. Node<E> next;
  4. Node<E> prev;
  5. }

每个链表存储了 first 和 last 指针:

  1. transient Node<E> first;
  2. transient Node<E> last;

1.png

2. 与 ArrayList 的比较

ArrayList 基于动态数组实现,LinkedList 基于双向链表实现。ArrayList 和 LinkedList 的区别可以归结为数组和链表的区别:

  • 数组支持随机访问,但插入删除的代价很高,需要移动大量元素;
  • 链表不支持随机访问,但插入删除只需要改变指针。

3.使用图解析

解析这个程序
image.png
分析
Node first,last 初始化为null 总的程序图
image.png image.png

l=last,new Node last=newNode
image.pngimage.png
if(l==null)… l=last 第二轮
image.pngimage.png
new Node 第二轮 last=newNode和l.next=newNode
image.pngimage.png

HashMap

为了便于理解,以下源码分析以 JDK 1.7 为主。

1. 存储结构

内部包含了一个 Entry 类型的数组 table。Entry 存储着键值对。它包含了四个字段,从 next 字段我们可以看出 Entry 是一个链表。即数组中的每个位置被当成一个桶,一个桶存放一个链表。HashMap 使用拉链法来解决冲突,同一个链表中存放哈希值和散列桶取模运算结果相同的 Entry。
2.png

  1. transient Entry[] table;
  1. tatic class Entry<K,V> implements Map.Entry<K,V> {
  2. final K key;
  3. V value;
  4. Entry<K,V> next;
  5. int hash;
  6. Entry(int h, K k, V v, Entry<K,V> n) {
  7. value = v;
  8. next = n;
  9. key = k;
  10. hash = h;
  11. }
  12. public final K getKey() {
  13. return key;
  14. }
  15. public final V getValue() {
  16. return value;
  17. }
  18. public final V setValue(V newValue) {
  19. V oldValue = value;
  20. value = newValue;
  21. return oldValue;
  22. }
  23. public final boolean equals(Object o) {
  24. if (!(o instanceof Map.Entry))
  25. return false;
  26. Map.Entry e = (Map.Entry)o;
  27. Object k1 = getKey();
  28. Object k2 = e.getKey();
  29. if (k1 == k2 || (k1 != null && k1.equals(k2))) {
  30. Object v1 = getValue();
  31. Object v2 = e.getValue();
  32. if (v1 == v2 || (v1 != null && v1.equals(v2)))
  33. return true;
  34. }
  35. return false;
  36. }
  37. public final int hashCode() {
  38. return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
  39. }
  40. public final String toString() {
  41. return getKey() + "=" + getValue();
  42. }
  43. }


2. 拉链法的工作原理

  1. HashMap<String, String> map = new HashMap<>();
  2. map.put("K1", "V1");
  3. map.put("K2", "V2");
  4. map.put("K3", "V3");
  • 新建一个 HashMap,默认大小为 16;
  • 插入 键值对,先计算 K1 的 hashCode 为 115,使用除留余数法得到所在的桶下标 115%16=3。
  • 插入 键值对,先计算 K2 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6。
  • 插入 键值对,先计算 K3 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6,插在 前面。

应该注意到链表的插入是以头插法方式进行的,例如上面的 不是插在 后面,而是插入在链表头部。
查找需要分成两步进行:

  • 计算键值对所在的桶;
  • 在链表上顺序查找,时间复杂度显然和链表的长度成正比。

3.png


3. put 操作

  1. public V put(K key, V value) {
  2. if (table == EMPTY_TABLE) {
  3. inflateTable(threshold);
  4. }
  5. // 键为 null 单独处理
  6. if (key == null)
  7. return putForNullKey(value);
  8. int hash = hash(key);
  9. // 确定桶下标
  10. int i = indexFor(hash, table.length);
  11. // 先找出是否已经存在键为 key 的键值对,如果存在的话就更新这个键值对的值为 value
  12. for (Entry<K,V> e = table[i]; e != null; e = e.next) {
  13. Object k;
  14. if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
  15. V oldValue = e.value;
  16. e.value = value;
  17. e.recordAccess(this);
  18. return oldValue;
  19. }
  20. }
  21. modCount++;
  22. // 插入新键值对
  23. addEntry(hash, key, value, i);
  24. return null;
  25. }

HashMap 允许插入键为 null 的键值对。但是因为无法调用 null 的 hashCode() 方法,也就无法确定该键值对的桶下标,只能通过强制指定一个桶下标来存放。HashMap 使用第 0 个桶存放键为 null 的键值对。

  1. private V putForNullKey(V value) {
  2. for (Entry<K,V> e = table[0]; e != null; e = e.next) {
  3. if (e.key == null) {
  4. V oldValue = e.value;
  5. e.value = value;
  6. e.recordAccess(this);
  7. return oldValue;
  8. }
  9. }
  10. modCount++;
  11. addEntry(0, null, value, 0);
  12. return null;
  13. }

使用链表的头插法,也就是新的键值对插在链表的头部,而不是链表的尾部。

  1. void addEntry(int hash, K key, V value, int bucketIndex) {
  2. if ((size >= threshold) && (null != table[bucketIndex])) {
  3. resize(2 * table.length);
  4. hash = (null != key) ? hash(key) : 0;
  5. bucketIndex = indexFor(hash, table.length);
  6. }
  7. createEntry(hash, key, value, bucketIndex);
  8. }
  9. void createEntry(int hash, K key, V value, int bucketIndex) {
  10. Entry<K,V> e = table[bucketIndex];
  11. // 头插法,链表头部指向新的键值对
  12. table[bucketIndex] = new Entry<>(hash, key, value, e);
  13. size++;
  14. }
  1. Entry(int h, K k, V v, Entry<K,V> n) {
  2. value = v;
  3. next = n;
  4. key = k;
  5. hash = h;
  6. }

4. 确定桶下标

很多操作都需要先确定一个键值对所在的桶下标。

  1. int hash = hash(key);
  2. int i = indexFor(hash, table.length);

4.1 计算 hash 值

  1. final int hash(Object k) {
  2. int h = hashSeed;
  3. if (0 != h && k instanceof String) {
  4. return sun.misc.Hashing.stringHash32((String) k);
  5. }
  6. h ^= k.hashCode();
  7. // This function ensures that hashCodes that differ only by
  8. // constant multiples at each bit position have a bounded
  9. // number of collisions (approximately 8 at default load factor).
  10. h ^= (h >>> 20) ^ (h >>> 12);
  11. return h ^ (h >>> 7) ^ (h >>> 4);
  12. }
  1. public final int hashCode() {
  2. return Objects.hashCode(key) ^ Objects.hashCode(value);
  3. }

4.2 取模
令 x = 1<<4,即 x 为 2 的 4 次方,它具有以下性质:

  1. x : 00010000
  2. x-1 : 00001111

令一个数 y 与 x-1 做与运算,可以去除 y 位级表示的第 4 位以上数:

  1. y : 10110010
  2. x-1 : 00001111
  3. y&(x-1) : 00000010

这个性质和 y 对 x 取模效果是一样的:

  1. y : 10110010
  2. x : 00010000
  3. y%x : 00000010

我们知道,位运算的代价比求模运算小的多,因此在进行这种计算时用位运算的话能带来更高的性能。
确定桶下标的最后一步是将 key 的 hash 值对桶个数取模:hash%capacity,如果能保证 capacity 为 2 的 n 次方,那么就可以将这个操作转换为位运算。

  1. static int indexFor(int h, int length) {
  2. return h & (length-1);
  3. }

扩容-基本原理

设 HashMap 的 table 长度为 M,需要存储的键值对数量为 N,如果哈希函数满足均匀性的要求,那么每条链表的长度大约为 N/M,因此查找的复杂度为 O(N/M)。
为了让查找的成本降低,应该使 N/M 尽可能小,因此需要保证 M 尽可能大,也就是说 table 要尽可能大。HashMap 采用动态扩容来根据当前的 N 值来调整 M 值,使得空间效率和时间效率都能得到保证。
和扩容相关的参数主要有:capacity、size、threshold 和 load_factor。

参数 含义
capacity table 的容量大小,默认为 16。需要注意的是 capacity 必须保证为 2 的 n 次方。
size 键值对数量。
threshold size 的临界值,当 size 大于等于 threshold 就必须进行扩容操作。
loadFactor 装载因子,table 能够使用的比例,threshold = (int)(capacity* loadFactor)。
  1. static final int DEFAULT_INITIAL_CAPACITY = 16;
  2. static final int MAXIMUM_CAPACITY = 1 << 30;
  3. static final float DEFAULT_LOAD_FACTOR = 0.75f;
  4. transient Entry[] table;
  5. transient int size;
  6. int threshold;
  7. final float loadFactor;
  8. transient int modCount;

从下面的添加元素代码中可以看出,当需要扩容时,令 capacity 为原来的两倍。

  1. void addEntry(int hash, K key, V value, int bucketIndex) {
  2. Entry<K,V> e = table[bucketIndex];
  3. table[bucketIndex] = new Entry<>(hash, key, value, e);
  4. if (size++ >= threshold)
  5. resize(2 * table.length);
  6. }

扩容使用 resize() 实现,需要注意的是,扩容操作同样需要把 oldTable 的所有键值对重新插入 newTable 中,因此这一步是很费时的。

  1. void resize(int newCapacity) {
  2. Entry[] oldTable = table;
  3. int oldCapacity = oldTable.length;
  4. if (oldCapacity == MAXIMUM_CAPACITY) {
  5. threshold = Integer.MAX_VALUE;
  6. return;
  7. }
  8. Entry[] newTable = new Entry[newCapacity];
  9. transfer(newTable);
  10. table = newTable;
  11. threshold = (int)(newCapacity * loadFactor);
  12. }
  13. void transfer(Entry[] newTable) {
  14. Entry[] src = table;
  15. int newCapacity = newTable.length;
  16. for (int j = 0; j < src.length; j++) {
  17. Entry<K,V> e = src[j];
  18. if (e != null) {
  19. src[j] = null;
  20. do {
  21. Entry<K,V> next = e.next;
  22. int i = indexFor(e.hash, newCapacity);
  23. e.next = newTable[i];
  24. newTable[i] = e;
  25. e = next;
  26. } while (e != null);
  27. }
  28. }
  29. }

6. 扩容-重新计算桶下标

在进行扩容时,需要把键值对重新计算桶下标,从而放到对应的桶上。在前面提到,HashMap 使用 hash%capacity 来确定桶下标。HashMap capacity 为 2 的 n 次方这一特点能够极大降低重新计算桶下标操作的复杂度。
假设原数组长度 capacity 为 16,扩容之后 new capacity 为 32:

  1. capacity : 00010000
  2. new capacity : 00100000

对于一个 Key,它的哈希值 hash 在第 5 位:

  • 为 0,那么 hash%00010000 = hash%00100000,桶位置和原来一致;
  • 为 1,hash%00010000 = hash%00100000 + 16,桶位置是原位置 + 16

    7. 计算数组容量

    HashMap 构造函数允许用户传入的容量不是 2 的 n 次方,因为它可以自动地将传入的容量转换为 2 的 n 次方。
    先考虑如何求一个数的掩码,对于 10010000,它的掩码为 11111111,可以使用以下方法得到:

    1. mask |= mask >> 1 11011000
    2. mask |= mask >> 2 11111110
    3. mask |= mask >> 4 11111111

    mask+1 是大于原始数字的最小的 2 的 n 次方。

    1. num 10010000
    2. mask+1 100000000

    以下是 HashMap 中计算数组容量的代码:

    1. static final int tableSizeFor(int cap) {
    2. int n = cap - 1;
    3. n |= n >>> 1;
    4. n |= n >>> 2;
    5. n |= n >>> 4;
    6. n |= n >>> 8;
    7. n |= n >>> 16;
    8. return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    9. }

    8. 链表转红黑树

    从 JDK 1.8 开始,一个桶存储的链表长度大于等于 8 时会将链表转换为红黑树。

    9. 与 Hashtable 的比较

  • Hashtable 使用 synchronized 来进行同步。

  • HashMap 可以插入键为 null 的 Entry。
  • HashMap 的迭代器是 fail-fast 迭代器。
  • HashMap 不能保证随着时间的推移 Map 中的元素次序是不变的。

    ConcurrentHashMap

    1. 存储结构

    1.png

    1. static final class HashEntry<K,V> {
    2. final int hash;
    3. final K key;
    4. volatile V value;
    5. volatile HashEntry<K,V> next;
    6. }

    ConcurrentHashMap 和 HashMap 实现上类似,最主要的差别是 ConcurrentHashMap 采用了分段锁(Segment),每个分段锁维护着几个桶(HashEntry),多个线程可以同时访问不同分段锁上的桶,从而使其并发度更高(并发度就是 Segment 的个数)。
    Segment 继承自 ReentrantLock。

    1. static final class Segment<K,V> extends ReentrantLock implements Serializable {
    2. private static final long serialVersionUID = 2249069246763182397L;
    3. static final int MAX_SCAN_RETRIES =
    4. Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
    5. transient volatile HashEntry<K,V>[] table;
    6. transient int count;
    7. transient int modCount;
    8. transient int threshold;
    9. final float loadFactor;
    10. }
    1. final Segment<K,V>[] segments;

    默认的并发级别为 16,也就是说默认创建 16 个 Segment。

    1. static final int DEFAULT_CONCURRENCY_LEVEL = 16;

    2. size 操作

    每个 Segment 维护了一个 count 变量来统计该 Segment 中的键值对个数。

    1. /**
    2. * The number of elements. Accessed only either within locks
    3. * or among other volatile reads that maintain visibility.
    4. */
    5. transient int count;

    在执行 size 操作时,需要遍历所有 Segment 然后把 count 累计起来。
    ConcurrentHashMap 在执行 size 操作时先尝试不加锁,如果连续两次不加锁操作得到的结果一致,那么可以认为这个结果是正确的。
    尝试次数使用 RETRIES_BEFORE_LOCK 定义,该值为 2,retries 初始值为 -1,因此尝试次数为 3。
    如果尝试的次数超过 3 次,就需要对每个 Segment 加锁。 ```java /**

    • Number of unsynchronized retries in size and containsValue
    • methods before resorting to locking. This is used to avoid
    • unbounded retries if tables undergo continuous modification
    • which would make it impossible to obtain an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2;

public int size() { // Try a few times to get accurate count. On failure due to // continuous async changes in table, resort to locking. final Segment[] segments = this.segments; int size; boolean overflow; // true if size overflows 32 bits long sum; // sum of modCounts long last = 0L; // previous sum int retries = -1; // first iteration isn’t retry try { for (;;) { // 超过尝试次数,则对每个 Segment 加锁 if (retries++ == RETRIES_BEFORE_LOCK) { for (int j = 0; j < segments.length; ++j) ensureSegment(j).lock(); // force creation } sum = 0L; size = 0; overflow = false; for (int j = 0; j < segments.length; ++j) { Segment seg = segmentAt(segments, j); if (seg != null) { sum += seg.modCount; int c = seg.count; if (c < 0 || (size += c) < 0) overflow = true; } } // 连续两次得到的结果一致,则认为这个结果是正确的 if (sum == last) break; last = sum; } } finally { if (retries > RETRIES_BEFORE_LOCK) { for (int j = 0; j < segments.length; ++j) segmentAt(segments, j).unlock(); } } return overflow ? Integer.MAX_VALUE : size; }

  1. <a name="igP8j"></a>
  2. #### 3. JDK 1.8 的改动
  3. JDK 1.7 使用分段锁机制来实现并发更新操作,核心类为 Segment,它继承自重入锁 ReentrantLock,并发度与 Segment 数量相等。<br />JDK 1.8 使用了 CAS 操作来支持更高的并发度,在 CAS 操作失败时使用内置锁 synchronized。<br />并且 JDK 1.8 的实现也在链表过长时会转换为红黑树。
  4. <a name="hlkL6"></a>
  5. ### LinkedHashMap
  6. <a name="oDou9"></a>
  7. #### 存储结构
  8. 继承自 HashMap,因此具有和 HashMap 一样的快速查找特性。
  9. ```java
  10. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

内部维护了一个双向链表,用来维护插入顺序或者 LRU 顺序。

  1. /**
  2. * The head (eldest) of the doubly linked list.
  3. */
  4. transient LinkedHashMap.Entry<K,V> head;
  5. /**
  6. * The tail (youngest) of the doubly linked list.
  7. */
  8. transient LinkedHashMap.Entry<K,V> tail;

accessOrder 决定了顺序,默认为 false,此时维护的是插入顺序。

  1. final boolean accessOrder;

LinkedHashMap 最重要的是以下用于维护顺序的函数,它们会在 put、get 等方法中调用。

  1. void afterNodeAccess(Node<K,V> p) { }
  2. void afterNodeInsertion(boolean evict) { }

afterNodeAccess()

当一个节点被访问时,如果 accessOrder 为 true,则会将该节点移到链表尾部。也就是说指定为 LRU 顺序之后,在每次访问一个节点时,会将这个节点移到链表尾部,保证链表尾部是最近访问的节点,那么链表首部就是最近最久未使用的节点。

  1. void afterNodeAccess(Node<K,V> e) { // move node to last
  2. LinkedHashMap.Entry<K,V> last;
  3. if (accessOrder && (last = tail) != e) {
  4. LinkedHashMap.Entry<K,V> p =
  5. (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
  6. p.after = null;
  7. if (b == null)
  8. head = a;
  9. else
  10. b.after = a;
  11. if (a != null)
  12. a.before = b;
  13. else
  14. last = b;
  15. if (last == null)
  16. head = p;
  17. else {
  18. p.before = last;
  19. last.after = p;
  20. }
  21. tail = p;
  22. ++modCount;
  23. }
  24. }

afterNodeInsertion()

在 put 等操作之后执行,当 removeEldestEntry() 方法返回 true 时会移除最晚的节点,也就是链表首部节点 first。
evict 只有在构建 Map 的时候才为 false,在这里为 true。

  1. void afterNodeInsertion(boolean evict) { // possibly remove eldest
  2. LinkedHashMap.Entry<K,V> first;
  3. if (evict && (first = head) != null && removeEldestEntry(first)) {
  4. K key = first.key;
  5. removeNode(hash(key), key, null, false, true);
  6. }
  7. }

removeEldestEntry() 默认为 false,如果需要让它为 true,需要继承 LinkedHashMap 并且覆盖这个方法的实现,这在实现 LRU 的缓存中特别有用,通过移除最近最久未使用的节点,从而保证缓存空间足够,并且缓存的数据都是热点数据。

  1. protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
  2. return false;
  3. }

LRU 缓存

以下是使用 LinkedHashMap 实现的一个 LRU 缓存:

  • 设定最大缓存空间 MAX_ENTRIES 为 3;
  • 使用 LinkedHashMap 的构造函数将 accessOrder 设置为 true,开启 LRU 顺序;
  • 覆盖 removeEldestEntry() 方法实现,在节点多于 MAX_ENTRIES 就会将最近最久未使用的数据移除。

    1. class LRUCache<K, V> extends LinkedHashMap<K, V> {
    2. private static final int MAX_ENTRIES = 3;
    3. protected boolean removeEldestEntry(Map.Entry eldest) {
    4. return size() > MAX_ENTRIES;
    5. }
    6. LRUCache() {
    7. super(MAX_ENTRIES, 0.75f, true);
    8. }
    9. }
    1. public static void main(String[] args) {
    2. LRUCache<Integer, String> cache = new LRUCache<>();
    3. cache.put(1, "a");
    4. cache.put(2, "b");
    5. cache.put(3, "c");
    6. cache.get(1);
    7. cache.put(4, "d");
    8. System.out.println(cache.keySet());
    9. }
    1. [3, 1, 4]

    WeakHashMap

    存储结构

    WeakHashMap 的 Entry 继承自 WeakReference,被 WeakReference 关联的对象在下一次垃圾回收时会被回收。
    WeakHashMap 主要用来实现缓存,通过使用 WeakHashMap 来引用缓存对象,由 JVM 对这部分缓存进行回收。

    1. private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>

    ConcurrentCache

    Tomcat 中的 ConcurrentCache 使用了 WeakHashMap 来实现缓存功能。
    ConcurrentCache 采取的是分代缓存:

  • 经常使用的对象放入 eden 中,eden 使用 ConcurrentHashMap 实现,不用担心会被回收(伊甸园);

  • 不常用的对象放入 longterm,longterm 使用 WeakHashMap 实现,这些老对象会被垃圾收集器回收。
  • 当调用 get() 方法时,会先从 eden 区获取,如果没有找到的话再到 longterm 获取,当从 longterm 获取到就把对象放入 eden 中,从而保证经常被访问的节点不容易被回收。
  • 当调用 put() 方法时,如果 eden 的大小超过了 size,那么就将 eden 中的所有对象都放入 longterm 中,利用虚拟机回收掉一部分不经常使用的对象。

    1. public final class ConcurrentCache<K, V> {
    2. private final int size;
    3. private final Map<K, V> eden;
    4. private final Map<K, V> longterm;
    5. public ConcurrentCache(int size) {
    6. this.size = size;
    7. this.eden = new ConcurrentHashMap<>(size);
    8. this.longterm = new WeakHashMap<>(size);
    9. }
    10. public V get(K k) {
    11. V v = this.eden.get(k);
    12. if (v == null) {
    13. v = this.longterm.get(k);
    14. if (v != null)
    15. this.eden.put(k, v);
    16. }
    17. return v;
    18. }
    19. public void put(K k, V v) {
    20. if (this.eden.size() >= size) {
    21. this.longterm.putAll(this.eden);
    22. this.eden.clear();
    23. }
    24. this.eden.put(k, v);
    25. }
    26. }