构造方法

  • jdk 1.7 ConcurrentHashMap 如果指定初始容量为32 那么就是32 但是jdk1.8 是 64
  • 可以看到实现了懒惰初始化,在构造方法中仅仅计算了 table 的大小,以后在第一次使用时才会真正创建
    1. public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
    2. if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
    3. throw new IllegalArgumentException();
    4. if (initialCapacity < concurrencyLevel) // Use at least as many bins 初始容量< 并发度
    5. initialCapacity = concurrencyLevel; // as estimated threads
    6. long size = (long)(1.0 + (long)initialCapacity / loadFactor);
    7. // tableSizeFor 仍然是保证计算的大小是 2^n, 即 16,32,64 ...
    8. int cap = (size >= (long)MAXIMUM_CAPACITY) ?
    9. MAXIMUM_CAPACITY : tableSizeFor((int)size);
    10. this.sizeCtl = cap;
    11. }