Java PriorityBlockingQueの原理分析

66956 ワード

PriorityBlockingQueは、システムリソースが尽きるまで、優先順位をサポートする無境界ブロック列です。デフォルトでは、要素は自然な順序で昇順に並べられます。また、カスタムクラスでcompreTo()メソッドを実現して、要素の並べ替え規則を指定したり、PriorityBlockingQueを初期化したときに、構造パラメータCompratorを指定して要素を並べ替えたりすることもできます。ただし、同じ優先要素の順序が保証されていないことに注意が必要です。PriorityBlockingQueも最小二叉スタックに基づいて実現され、CASに基づいて実現されたスピンロックを使ってキューのダイナミック拡がりを制御し、拡張操作がtake操作の実行を妨げないことを保証しました。
PriorityBlockingQueは、4つの構造方法があります。/デフォルトの構造方法は、this(DEFAULTUINITIAL LuCAPACITY,null)を呼び出します。すなわち、デフォルトの容量は11 public PriotyBlockingQue()/initial Capacityに基づいて、キューの初期容量を設定します。compratorオブジェクトに基づいてデータを並べ替えます。public PriorityBlockingQue/集合によってキューpublic Priority BlockingQueを作成します。
public class PriorityBlockingQueue<E> extends AbstractQueue<E>
    implements BlockingQueue<E>, java.io.Serializable {
   private static final long serialVersionUID = 5595510919245408276L;
   private static final int DEFAULT_INITIAL_CAPACITY = 11;
   private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
   private transient Object[] queue;
   private transient int size;
   private transient Comparator<? super E> comparator;
   private final ReentrantLock lock;
   private final Condition notEmpty;
   private transient volatile int allocationSpinLock;//      ,   
   private PriorityQueue<E> q;//        ,writeObject readObject  。          ,              
   
   public PriorityBlockingQueue(int initialCapacity,
                                 Comparator<? super E> comparator) {
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        this.comparator = comparator;
        this.queue = new Object[initialCapacity];   //         allocationSpinLock,q
  } 
  public PriorityBlockingQueue(Collection<? extends E> c) {
        this.lock = new ReentrantLock();
        this.notEmpty = lock.newCondition();
        boolean heapify = true; // true if not known to be in heap order
        boolean screen = true;  // true if must screen for nulls
        if (c instanceof SortedSet<?>) {//           ,         
            SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
            this.comparator = (Comparator<? super E>) ss.comparator();
            heapify = false;//      
        }//        PriorityBlockingQueue  ,        
        else if (c instanceof PriorityBlockingQueue<?>) {
            PriorityBlockingQueue<? extends E> pq =
                (PriorityBlockingQueue<? extends E>) c;
            this.comparator = (Comparator<? super E>) pq.comparator();
            screen = false;
            if (pq.getClass() == PriorityBlockingQueue.class) // exact match
                heapify = false;//      
        }
        Object[] a = c.toArray();
        int n = a.length;
        // If c.toArray incorrectly doesn't return Object[], copy it.
        if (a.getClass() != Object[].class)
            a = Arrays.copyOf(a, n, Object[].class);
        if (screen && (n == 1 || this.comparator != null)) {
            for (int i = 0; i < n; ++i)
                if (a[i] == null)
                    throw new NullPointerException();
        }
        this.queue = a;
        this.size = n;
        if (heapify)
            heapify();//   
    }  
  private void removeAt(int i) {
        Object[] array = queue;
        int n = size - 1;
        if (n == i) // removed last element
            array[i] = null;
        else {
            E moved = (E) array[n];
            array[n] = null;
            Comparator<? super E> cmp = comparator;
            if (cmp == null)
                siftDownComparable(i, moved, array, n);
            else
                siftDownUsingComparator(i, moved, array, n, cmp);
            if (array[i] == moved) {
                if (cmp == null)
                    siftUpComparable(i, moved, array);
                else
                    siftUpUsingComparator(i, moved, array, cmp);
            }
        }
        size = n;
    }
  private static <T> void siftDownComparable(int k, T x, Object[] array,
                                               int n) {//  x  k   
        if (n > 0) {
            Comparable<? super T> key = (Comparable<? super T>)x;
            int half = n >>> 1;           // loop while a non-leaf
            while (k < half) {
                int child = (k << 1) + 1; // assume left child is least
                Object c = array[child];
                int right = child + 1;
                if (right < n &&
                    ((Comparable<? super T>) c).compareTo((T) array[right]) > 0)
                    c = array[child = right];
                if (key.compareTo((T) c) <= 0)//        ,  
                    break;
                array[k] = c;
                k = child;
            }
            array[k] = key;
        }
    }    
  private static <T> void siftUpComparable(int k, T x, Object[] array) {//  x  k   
        Comparable<? super T> key = (Comparable<? super T>) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = array[parent];
            if (key.compareTo((T) e) >= 0)//       ,  
                break;
            array[k] = e;
            k = parent;
        }
        array[k] = key;
    }  
 public boolean offer(E e) {
        if (e == null)//        null,     NullPointerException  
            throw new NullPointerException();
        final ReentrantLock lock = this.lock;
        lock.lock();
        int n, cap;
        Object[] array;
        while ((n = size) >= (cap = (array = queue).length))
            tryGrow(array, cap);
        try {
            Comparator<? super E> cmp = comparator;
            if (cmp == null)
                siftUpComparable(n, e, array);//      size   
            else
                siftUpUsingComparator(n, e, array, cmp);
            size = n + 1;
            notEmpty.signal();//           
        } finally {
            lock.unlock();
        }
        return true;
    }   
  public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        E result;
        try {
            while ( (result = dequeue()) == null)
                notEmpty.await();
        } finally {
            lock.unlock();
        }
        return result;
    }
  public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        E result;
        try {
            while ( (result = dequeue()) == null && nanos > 0)
                nanos = notEmpty.awaitNanos(nanos);
        } finally {
            lock.unlock();
        }
        return result;
    }    
   public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (size == 0) ? null : (E) queue[0];
        } finally {
            lock.unlock();
        }
    } 
  public int size() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return size;
        } finally {
            lock.unlock();
        }
    }  
  private int indexOf(Object o) {
        if (o != null) {
            Object[] array = queue;
            int n = size;
            for (int i = 0; i < n; i++)
                if (o.equals(array[i]))
                    return i;
        }
        return -1;
    }
  public boolean remove(Object o) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int i = indexOf(o);
            if (i == -1)
                return false;
            removeAt(i);
            return true;
        } finally {
            lock.unlock();
        }
    }
   public boolean contains(Object o) {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return indexOf(o) != -1;
        } finally {
            lock.unlock();
        }
    }
   private E dequeue() {
        int n = size - 1;
        if (n < 0)
            return null;
        else {
            Object[] array = queue;
            E result = (E) array[0];
            E x = (E) array[n];
            array[n] = null;
            Comparator<? super E> cmp = comparator;
            if (cmp == null)
                siftDownComparable(0, x, array, n);
            else
                siftDownUsingComparator(0, x, array, n, cmp);
            size = n;
            return result;
        }
    }  
   private void heapify() {
        Object[] array = queue;
        int n = size;
        int half = (n >>> 1) - 1;
        Comparator<? super E> cmp = comparator;
        if (cmp == null) {
            for (int i = half; i >= 0; i--)
                siftDownComparable(i, (E) array[i], array, n);//      
        }
        else {
            for (int i = half; i >= 0; i--)
                siftDownUsingComparator(i, (E) array[i], array, n, cmp);
        }
    } 
  public void clear() {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] array = queue;
        int n = size;
        size = 0;
        for (int i = 0; i < n; i++)
            array[i] = null;
    } finally {
        lock.unlock();
    }
   public int drainTo(Collection<? super E> c, int maxElements) {//      
        if (c == null)
            throw new NullPointerException();
        if (c == this)
            throw new IllegalArgumentException();
        if (maxElements <= 0)
            return 0;
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            int n = Math.min(size, maxElements);
            for (int i = 0; i < n; i++) {//     ,        ;
                c.add((E) queue[0]); // In this order, in case add() throws.
                dequeue();
            }
            return n;
        } finally {
            lock.unlock();
        }
    } 
}
放して、取って、取り除く時すべてロックをプラスして、同時に1つのスレッドだけが操作します。prvate PriorityQue q//配列実現の最小スタックは、writeObjectとreadObjectが使用されます。
private void writeObject(java.io.ObjectOutputStream s)
       throws java.io.IOException {
       lock.lock();
       try {
           // avoid zero capacity argument
           q = new PriorityQueue<E>(Math.max(size, 1), comparator);
           q.addAll(this);
           s.defaultWriteObject();
       } finally {
           q = null;
           lock.unlock();
       }
   }
private void readObject(java.io.ObjectInputStream s)
       throws java.io.IOException, ClassNotFoundException {
       try {
           s.defaultReadObject();
           int sz = q.size();
           SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, sz);
           this.queue = new Object[sz];
           comparator = q.comparator();
           addAll(q);
       } finally {
           q = null;
       }
   }
prvate tranient volatile int allocationSpinlock;//拡張時に使う
拡張しないと正常にロックを取って元素を入れます。
拡張時にロックが解除されました。取ったスレッドがロックを取ったら取り外しができます。offerのスレッドがロックを取ったら放してもいいです。他のスレッドはこの方法に入れてもいいです。他のスレッドはロックを入れる方法もあります。ロックを解除してallocationSpinlockロックをかけました。