對數據結構情有獨鍾,打算慢慢把jdk裏的實現都讀一遍,發現其中的亮點,持續更新。java
這應該是咱們學習java最先接觸的到的數據結構,衆所周知,數組在申請了內存以後,沒法擴展;而數組隊列,是實現了動態擴容的功能,意義上是爲動態數組,實際上的數組擴容是不容許在原地址上伸長的,很簡單,由於在你申請的數組空間以後,可能存在別的被申請掉的內存;要實現動態數組,必然是新申請一個更大的連續內存空間,並替換到原來的引用中。數組
從構造函數,能夠清楚看到,elementData,就是這個存儲數據的內存地址。數據結構
而後,找到添加的接口,add;在真正賦值以前,會進行grow方法。多線程
能夠看到,真正幹活的是這個copyof,找到最後,就是這個方法。併發
首先這個泛型數組,會先判斷一下若是是Object父類,則直接new Object,若是不是則調用Arrays的接口建立,纔去新建一個數組,而後就會去拷貝數組到新的數組,並返回這個被拷貝的數組。ide
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { @SuppressWarnings("unchecked") T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
它的get方法,簡單判斷一下是否大於元素容量,防止內存泄漏的操做。函數
public E get(int index) { rangeCheck(index); return elementData(index); }
它的remove方法,是將這個位置以後的全部元素,前移一個位置,並將最後的元素設置爲null。oop
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
它提供的排序接口,設計的是傳入一個比較器,能夠自定升序仍是降序,最終一個分支使用的是mergeSort。最後還校驗了一下modcount,先後是否相等,若是不相等拋出併發異常,有點CAS的思想。學習
@Override @SuppressWarnings("unchecked") public void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, size, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; }
public static void sort(Object[] a) { if (LegacyMergeSort.userRequested) legacyMergeSort(a); else ComparableTimSort.sort(a, 0, a.length, null, 0, 0); }
長度小於7插入排序,反正是個n平方的排序,this
private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off) { int length = high - low; // Insertion sort on smallest arrays if (length < INSERTIONSORT_THRESHOLD) { for (int i=low; i<high; i++) for (int j=i; j>low && ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--) swap(dest, j, j-1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) >>> 1; mergeSort(dest, src, low, mid, -off); mergeSort(dest, src, mid, high, -off); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for(int i = destLow, p = low, q = mid; i < destHigh; i++) { if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0) dest[i] = src[p++]; else dest[i] = src[q++]; } }
優先隊列,讀做優先寫做二叉樹,也叫堆(大頂堆,小頂堆)。
它的實現方法是數組,使用數組作二叉樹,每一個元素e[i]的孩子爲e[2*i+1],e[2*i+2]。
找到添加元素的方法;比較器爲空的時候;它從末尾插入,先找出父親,若是父節點比本身大,則繼續往上,將父節點往下移動,直到找到比它小的位置插入,默認是一個小頂堆。
public boolean offer(E e) { if (e == null) throw new NullPointerException(); modCount++; int i = size; if (i >= queue.length) grow(i + 1); size = i + 1; if (i == 0) queue[0] = e; else siftUp(i, e); return true; } private void siftUpComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>) x; while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (key.compareTo((E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = key; }
彈出操做就是把堆定元素拿走,而後從末尾拿出一個元素,放在堆頂,不斷地下沉。
public E poll() { if (size == 0) return null; int s = --size; modCount++; E result = (E) queue[0]; E x = (E) queue[s]; queue[s] = null; if (s != 0) siftDown(0, x); return result; } private void siftDownComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>)x; int half = size >>> 1; // loop while a non-leaf while (k < half) { int child = (k << 1) + 1; // assume left child is least Object c = queue[child]; int right = child + 1; if (right < size && ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0) c = queue[child = right]; if (key.compareTo((E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = key; }
看膩了數組隊列,咱們來看多線程的阻塞隊列是怎麼實現的;
粗淺的看,它是在多線程中保持一致性的一種數據結構,保持一致性只有兩種思路:(1)假設它發生了衝突,則必然加鎖(悲觀)(2)假設他不必定產生衝突,CAS無鎖實現(樂觀);
固然,它最基本的數據都是數組;
public boolean offer(E e) { checkNotNull(e); final ReentrantLock lock = this.lock; lock.lock(); try { if (count == items.length) return false; else { enqueue(e); return true; } } finally { lock.unlock(); } }
從以上的代碼,很是直白,首先只能有一個線程進入這個數據操做的代碼,而且隊列是不擴容的,一旦達到最大容量,則直接拒絕,返回false;
private void enqueue(E x) { // assert lock.getHoldCount() == 1; // assert items[putIndex] == null; final Object[] items = this.items; items[putIndex] = x; if (++putIndex == items.length) putIndex = 0; count++; notEmpty.signal(); }
正如咱們認知的同樣,它是一個先進先出的隊列,因此在下標達到最大長度以後,會reset成0,而且入隊以後,還會喚醒一個事件,就是非空;
咱們還有一個put方法能夠入隊;
public void put(E e) throws InterruptedException { checkNotNull(e); final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == items.length) notFull.await(); enqueue(e); } finally { lock.unlock(); } }
這個隊列至關於不是快速失敗,而是將當前線程park,使用一個condition的await,讓線程等待;
它的獲取方法take,咱們來閱讀如下;
public E take() throws InterruptedException { final ReentrantLock lock = this.lock; lock.lockInterruptibly(); try { while (count == 0) notEmpty.await(); return dequeue(); } finally { lock.unlock(); } }
使用的是一個線程中斷鎖,而且在隊列爲空的時候,park當前線程;與入隊方法enqueue成對應,有元素進來的時候會signal阻塞在此的線程;
private E dequeue() { // assert lock.getHoldCount() == 1; // assert items[takeIndex] != null; final Object[] items = this.items; @SuppressWarnings("unchecked") E x = (E) items[takeIndex]; items[takeIndex] = null; if (++takeIndex == items.length) takeIndex = 0; count--; if (itrs != null) itrs.elementDequeued(); notFull.signal(); return x; }
這個操做,在結束的時候會喚醒阻塞在put的線程,告訴他有位置能夠進來了。
而此外,它還提供了帶等待時間的阻塞方法。
public boolean offer(E e, long timeout, TimeUnit unit) public E poll(long timeout, TimeUnit unit)
而後它的size,也是須要獲取重入鎖的,不是非阻塞的。
這麼看,它有點像--消息隊列。
併發無鎖鏈表隊列,由於線程不會被park,因此效率較高,可是可能引發cpu運算太高。它是在普通鏈表的基礎上,添加了併發的控制, 並採用CAS原子操做保證內存的有序寫入。
它的基本元素,Node,只有兩個屬性,原子的item和next。
java.util.concurrent.ConcurrentLinkedQueue.Node Node<E> volatile E item; volatile Node<E> next;
初始化的時候,head和tail都指向new出來的一個Node上。
head = tail = new Node<E>(null);
咱們只須要關心它的添加(offer)和獲取(poll)接口是什麼樣的流程就能夠了。
offer接口
public boolean offer(E e) { checkNotNull(e); final Node<E> newNode = new Node<E>(e); // 快照 for (Node<E> t = tail, p = t;;) { Node<E> q = p.next; if (q == null) {// 若是是隊尾 則嘗試CAS插入 if (p.casNext(null, newNode)) { // 若是tail節點在插入前不是指向末尾節點,則更新tail // 延遲更新也沒事,始終會有一個線程更新成功 if (p != t) casTail(t, newNode); // Failure is OK. return true; } // Lost CAS race to another thread; re-read next } else if (p == q) // 因爲poll方法,會將節點自引用以便gc,因此要從頭節點開始找 p = (t != (t = tail)) ? t : head; else // 若是t的引用地址和tail的一致,則p往下找(p=p.next的意思) // 若是不一致,則直接拿到tail並賦值給p p = (p != t && t != (t = tail)) ? t : q; } }
在單線程插入的時候,插入完成以後如上圖。若是繼續插入,則p和t不相等,會更新tail的值,這就是快照時候tail不是指向最後一個節點纔會執行的邏輯。
若是是多線程插入,在上一個線程沒有更新tail的時候,它可能會一直p=p.next的流程,這時候另外一個線程更新了tail的地址,這時候須要刷新t的位置。
offer和offer方法的多線程衝突,主要在於tail指針的位置問題。
接下來咱們看看poll方法。
public E poll() { restartFromHead: for (;;) { for (Node<E> h = head, p = h, q;;) { E item = p.item; // 出隊是更新節點data爲null if (item != null && p.casItem(item, null)) { // 若是p節點的下一個不爲空則head指向下一個,不然指向p updateHead(h, ((q = p.next) != null) ? q : p); return item; } else if ((q = p.next) == null) {// 若是下一個是null 則更新頭節點爲自引用 updateHead(h, p); return null; } else if (p == q)// 撞到了自引用 則跳出循環從新copy快照 continue restartFromHead; else p = q;// p = p.next的意思 } } }
咱們假設隊列的狀況是。h仍是指向head原地址,p通過一步以後會指向h的next。這時候要將p的Node的item更新爲null,並設置head指針,並且p.next不爲空,則head會更新到p.next上。
更新以後的狀態是。
若是這個時候tail沒有更新,仍是指向最初的那個節點,也就是offer與poll的衝突。這時候offer就會走第二個else if條件,拿到head。
只有三四行代碼,卻那麼多場景,真是大師做品。寫得這麼難懂,是由於能夠節省CAS指令,咱們本身寫的CAS操做是util success,這樣可能會執行不少條,它這裏的head和tail更新不強制必定成功。