publicclassArrayList<E>extendsAbstractList<E>implementsList<E>,RandomAccess,Cloneable,java.io.Serializable{// 默认初始化容量privatestaticfinalintDEFAULT_CAPACITY=10;// 初始化集合时使用,将 elementData 数组初始化为一个空数组privatestaticfinalObject[]EMPTY_ELEMENTDATA={};// 第一次添加数据时使用,默认情况下用于第一次扩容的判定依据privatestaticfinalObject[]DEFAULTCAPACITY_EMPTY_ELEMENTDATA={};transientObject[]elementData;// non-private to simplify nested class access// 容量privateintsize;publicArrayList(intinitialCapacity){if(initialCapacity>0){this.elementData=newObject[initialCapacity];}elseif(initialCapacity==0){this.elementData=EMPTY_ELEMENTDATA;}else{thrownewIllegalArgumentException("Illegal Capacity: "+initialCapacity);}}/** * Constructs an empty list with an initial capacity of ten. */publicArrayList(){this.elementData=DEFAULTCAPACITY_EMPTY_ELEMENTDATA;}}
publicclassHashSet<E>extendsAbstractSet<E>implementsSet<E>,Cloneable,java.io.Serializable{transientHashMap<E,Object>map;// Dummy value to associate with an Object in the backing MapstaticfinalObjectPRESENT=newObject();publicHashSet(){map=newHashMap<>();}HashSet(intinitialCapacity,floatloadFactor,booleandummy){map=newLinkedHashMap<>(initialCapacity,loadFactor);}}
publicclassTreeSet<E>extendsAbstractSet<E>implementsNavigableSet<E>,Cloneable,java.io.Serializable{privatetransientNavigableMap<E,Object>m;// Dummy value to associate with an Object in the backing MapprivatestaticfinalObjectPRESENT=newObject();TreeSet(NavigableMap<E,Object>m){this.m=m;}publicTreeSet(){this(newTreeMap<>());}publicTreeSet(Comparator<?superE>comparator){this(newTreeMap<>(comparator));}}
privatevoidgrow(intneeded){// overflow-conscious codefinalintoldCapacity=elements.length;intnewCapacity;// 容量小于64则2倍扩容,否则1.5倍扩容intjump=(oldCapacity<64)?(oldCapacity+2):(oldCapacity>>1);if(jump<needed||(newCapacity=(oldCapacity+jump))-MAX_ARRAY_SIZE>0)newCapacity=newCapacity(needed,jump);finalObject[]es=elements=Arrays.copyOf(elements,newCapacity);// Exceptionally, here tail == head needs to be disambiguatedif(tail<head||(tail==head&&es[head]!=null)){// 容量增量intnewSpace=newCapacity-oldCapacity;// 将head索引位之后的数据对象复制到从head+newSpace开始的索引上System.arraycopy(es,head,es,head+newSpace,oldCapacity-head);// 从head开始向后清理数据对象,重新定位headfor(inti=head,to=(head+=newSpace);i<to;i++)es[i]=null;}}
publicclassPriorityQueue<E>extendsAbstractQueue<E>implementsjava.io.Serializable{// 默认大小privatestaticfinalintDEFAULT_INITIAL_CAPACITY=11;/** * Priority queue represented as a balanced binary heap: the two * children of queue[n] are queue[2*n+1] and queue[2*(n+1)]. The * priority queue is ordered by comparator, or by the elements' * natural ordering, if comparator is null: For each node n in the * heap and each descendant d of n, n <= d. The element with the * lowest value is in queue[0], assuming the queue is nonempty. */transientObject[]queue;// non-private to simplify nested class access// 元素数量intsize;// 比较器privatefinalComparator<?superE>comparator;transientintmodCount;// non-private to simplify nested class accesspublicPriorityQueue(){this(DEFAULT_INITIAL_CAPACITY,null);}publicPriorityQueue(intinitialCapacity){this(initialCapacity,null);}publicPriorityQueue(Comparator<?superE>comparator){this(DEFAULT_INITIAL_CAPACITY,comparator);}publicPriorityQueue(intinitialCapacity,Comparator<?superE>comparator){// Note: This restriction of at least one is not actually needed,// but continues for 1.5 compatibilityif(initialCapacity<1)thrownewIllegalArgumentException();this.queue=newObject[initialCapacity];this.comparator=comparator;}}
// LinkedHashMap.Entry 继承 HashMap.Node, 间接继承 Map.EntrystaticfinalclassTreeNode<K,V>extendsLinkedHashMap.Entry<K,V>{TreeNode<K,V>parent;// red-black tree linksTreeNode<K,V>left;TreeNode<K,V>right;TreeNode<K,V>prev;// needed to unlink next upon deletion// 当前节点是红色还是黑色booleanred;TreeNode(inthash,Kkey,Vval,Node<K,V>next){super(hash,key,val,next);}}
finalVput(Kkey,inthash,Vvalue,booleanonlyIfAbsent){// 获取 ReentrantLock 独占锁,获取不到,scanAndLockForPut 获取。HashEntry<K,V>node=tryLock()?null:scanAndLockForPut(key,hash,value);VoldValue;try{HashEntry<K,V>[]tab=table;// 计算要put的数据位置intindex=(tab.length-1)&hash;// CAS 获取 index 坐标的值HashEntry<K,V>first=entryAt(tab,index);for(HashEntry<K,V>e=first;;){if(e!=null){// 检查是否 key 已经存在,如果存在,则遍历链表寻找位置,找到后替换 valueKk;if((k=e.key)==key||(e.hash==hash&&key.equals(k))){oldValue=e.value;if(!onlyIfAbsent){e.value=value;++modCount;}break;}e=e.next;}else{// first 有值没说明 index 位置已经有值了,有冲突,链表头插法。if(node!=null)node.setNext(first);elsenode=newHashEntry<K,V>(hash,key,value,first);intc=count+1;// 容量大于扩容阀值,小于最大容量,进行扩容if(c>threshold&&tab.length<MAXIMUM_CAPACITY)rehash(node);else// index 位置赋值 node,node 可能是一个元素,也可能是一个链表的表头setEntryAt(tab,index,node);++modCount;count=c;oldValue=null;break;}}}finally{unlock();}returnoldValue;}
publicclassConcurrentHashMap<K,V>extendsAbstractMap<K,V>implementsConcurrentMap<K,V>,Serializable{privatestaticfinalintMAXIMUM_CAPACITY=1<<30;privatestaticfinalintDEFAULT_CAPACITY=16;staticfinalintTREEIFY_THRESHOLD=8;staticfinalintUNTREEIFY_THRESHOLD=6;staticfinalintMIN_TREEIFY_CAPACITY=64;//常量:表示正在转移staticfinalintMOVED=-1;// 常量:表示已经转换成树staticfinalintTREEBIN=-2;// 常量:hash for transient reservationsstaticfinalintRESERVED=-3;// 常量:usable bits of normal node hashstaticfinalintHASH_BITS=0x7fffffff;//数组,用来保存元素transientvolatileNode<K,V>[]table;//转移时用的数组privatetransientvolatileNode<K,V>[]nextTable;/** * 用来控制表初始化和扩容的控制属性 */privatetransientvolatileintsizeCtl;//桶的节点放在table中可以作为一个链式的桶staticclassNode<K,V>implementsMap.Entry<K,V>{finalinthash;finalKkey;volatileVval;volatileNode<K,V>next;}//桶的树状节点staticfinalclassTreeNode<K,V>extendsNode<K,V>{TreeNode<K,V>parent;// red-black tree linksTreeNode<K,V>left;TreeNode<K,V>right;TreeNode<K,V>prev;// needed to unlink next upon deletionbooleanred;}//放在table中作为一个链式的桶staticfinalclassTreeBin<K,V>extendsNode<K,V>{TreeNode<K,V>root;volatileTreeNode<K,V>first;volatileThreadwaiter;volatileintlockState;}}
publicclassHashtable<K,V>extendsDictionary<K,V>implementsMap<K,V>,Cloneable,java.io.Serializable{/** * The hash table data. */privatetransientEntry<?,?>[]table;/** * The total number of entries in the hash table. */privatetransientintcount;/** * The table is rehashed when its size exceeds this threshold. (The * value of this field is (int)(capacity * loadFactor).) * * @serial */privateintthreshold;/** * The load factor for the hashtable. * * @serial */privatefloatloadFactor;privatestaticclassEntry<K,V>implementsMap.Entry<K,V>{finalinthash;finalKkey;Vvalue;Entry<K,V>next;}}
publicclassPriorityBlockingQueue<E>extendsAbstractQueue<E>implementsBlockingQueue<E>,java.io.Serializable{// 默认初始化大小privatestaticfinalintDEFAULT_INITIAL_CAPACITY=11;// 最大容量上限privatestaticfinalintMAX_ARRAY_SIZE=Integer.MAX_VALUE-8;// 小顶堆 数组存储privatetransientObject[]queue;// 当前队列大小privatetransientintsize;privatetransientComparator<?superE>comparator;/** * Lock used for all public operations */privatefinalReentrantLocklock;/** * Condition for blocking when empty */privatefinalConditionnotEmpty;// 主要用于队列的扩容过程,保证扩容不会重复进行privatetransientvolatileintallocationSpinLock;// 用于序列化和反序列化过程,避免多个JDK之间的兼容性问题privatePriorityQueue<E>q;}
// 扩容主要由offer()方法进行调用privatevoidtryGrow(Object[]array,intoldCap){// 释放当前线程获得的锁// 改用CAS思想进行扩容lock.unlock();// must release and then re-acquire main lockObject[]newArray=null;// 将allocationSpinLock 设置为1,保证成功设置allocationSpinLock为1的线程能进行真正的扩容操作if(allocationSpinLock==0&&UNSAFE.compareAndSwapInt(this,allocationSpinLockOffset,0,1)){try{// 小于64则2倍扩容,否则1.5倍扩容intnewCap=oldCap+((oldCap<64)?(oldCap+2):// grow faster if small(oldCap>>1));if(newCap-MAX_ARRAY_SIZE>0){// possible overflowintminCap=oldCap+1;if(minCap<0||minCap>MAX_ARRAY_SIZE)thrownewOutOfMemoryError();newCap=MAX_ARRAY_SIZE;}// 创建数组if(newCap>oldCap&&queue==array)newArray=newObject[newCap];}finally{allocationSpinLock=0;}}// 当前线程没有扩容操作权,让出CPU资源if(newArray==null)// back off if another thread is allocatingThread.yield();lock.lock();// 实际扩容操作,数组拷贝if(newArray!=null&&queue==array){queue=newArray;System.arraycopy(array,0,newArray,0,oldCap);}}