Java原始碼解析阻塞佇列ArrayBlockingQueue功能簡介
阿新 • • 發佈:2018-12-18
本文基於jdk1.8進行分析。
阻塞佇列是java開發時常用的一個數據結構。首先看一下阻塞佇列的作用是什麼。阻塞佇列的作用,從原始碼中類的註釋中來了解,是最清晰準確的。如下圖。
ArrayBlockingQueue是一個用陣列實現的有界阻塞佇列。提供FIFO的功能。佇列頭上的元素是在佇列中呆了最長時間的元素,佇列尾上的元素是在佇列中呆了時間最短的元素。新元素會插入在佇列尾部,從佇列獲取元素時會從佇列頭上獲取。
這是一個傳統的有界佇列,在這個有界佇列裡,一個固定大小的陣列用來儲存生產者產生的元素和消費者獲取的元素。一旦建立,大小不可改變。往已滿的佇列中嘗試新增元素,會阻塞操作。從空的佇列中獲取元素,也會阻塞操作。
這個類為等待中的生產著和消費者執行緒排序提供可選的公平策略。預設情況下,順序是沒有保證的。但是,一個用fairness=true建立的佇列可以保證FIFO特性。公平性通常會降低吞吐量,但是可以減少易變性並避免飢餓。
/** * A bounded {@linkplain BlockingQueue blocking queue} backed by an * array. This queue orders elements FIFO (first-in-first-out). The * <em>head</em> of the queue is that element that has been on the * queue the longest time. The <em>tail</em> of the queue is that * element that has been on the queue the shortest time. New elements * are inserted at the tail of the queue, and the queue retrieval * operations obtain elements at the head of the queue. * * <p>This is a classic "bounded buffer", in which a * fixed-sized array holds elements inserted by producers and * extracted by consumers. Once created, the capacity cannot be * changed. Attempts to {@code put} an element into a full queue * will result in the operation blocking; attempts to {@code take} an * element from an empty queue will similarly block. * * <p>This class supports an optional fairness policy for ordering * waiting producer and consumer threads. By default, this ordering * is not guaranteed. However, a queue constructed with fairness set * to {@code true} grants threads access in FIFO order. Fairness * generally decreases throughput but reduces variability and avoids * starvation. * * <p>This class and its iterator implement all of the * <em>optional</em> methods of the {@link Collection} and {@link * Iterator} interfaces. * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @since 1.5 * @author Doug Lea * @param <E> the type of elements held in this collection */