BoneCP中用于保存连接对象的队列为TransferQueue,该接口为jsr166y中的接口,继承BlockingQueue:
TransferQueue<ConnectionHandle> connectionHandles; public interface TransferQueue<E> extends BlockingQueue<E> { }
if (config.getMaxConnectionsPerPartition() == config.getMinConnectionsPerPartition()){ // if we have a pool that we don't want resized, make it even faster by ignoring // the size constraints. connectionHandles = queueLIFO ? new LIFOQueue<ConnectionHandle>() : new LinkedTransferQueue<ConnectionHandle>(); } else { connectionHandles = queueLIFO ? new LIFOQueue<ConnectionHandle>(this.config.getMaxConnectionsPerPartition()) : new BoundedLinkedTransferQueue<ConnectionHandle>(this.config.getMaxConnectionsPerPartition()); }
如果设置了queueLIFO,则使用LIFOQueue队列,该队列继承LinkedBlockingDeque:
public class LIFOQueue<E> extends LinkedBlockingDeque<E> implements TransferQueue<E>{ }
LIFOQueue借助父类的API来实现TransferQueue接口,并重写相应的方法,从FIFO队列变成了LIFO队列。
LinkedBlockingDeque
它基于双向双端链表,持有头节点和尾节点的引用。节点(Node)是一个静态内部类,它是存放队列元素的最小单位,并持有上一个节点和下一个节点的引用:
static final class Node<E> { E item; Node<E> prev; Node<E> next; Node(E x) { item = x; } }
该队列具有固定的容量,在构造时,一旦指定容量,将无法插入更多元素,容量字段capacity具有final修饰符,如果无法预计容量的上限,那么可以使用默认的构造方法,它使用Integer.MAX_VALUE作为容量值:
/** Maximum number of items in the deque */ private final int capacity; public LinkedBlockingDeque() { this(Integer.MAX_VALUE); } public LinkedBlockingDeque(int capacity) { if (capacity <= 0) throw new IllegalArgumentException(); this.capacity = capacity; }
该队列通过一个ReentrantLock对象和两个Condition对象来实现同步和阻塞(Condition的用法):
/** Main lock guarding all access */ final ReentrantLock lock = new ReentrantLock(); /** Condition for waiting takes */ private final Condition notEmpty = lock.newCondition(); /** Condition for waiting puts */ private final Condition notFull = lock.newCondition();
如果设置了config.getMaxConnectionsPerPartition() == config.getMinConnectionsPerPartition(),则使用LinkedTransferQueue,否则使用BoundedLinkedTransferQueue。
BoundedLinkedTransferQueue继承LinkedTransferQueue,通过限定容量来实现了该类的“有界(bounded)”版本。它使用了原子变量java.util.concurrent.atomic.AtomicInteger来保存链表的大小。并在offer方法中调用ReentrantLock的lock方法:
/** No of elements in queue. */ private AtomicInteger size = new AtomicInteger(); /** bound of queue. */ private final int maxQueueSize; /** Main lock guarding all access */ private final ReentrantLock lock = new ReentrantLock(); public BoundedLinkedTransferQueue(int maxQueueSize){ this.maxQueueSize = maxQueueSize; }