BoneCP源码——BoneCP中使用的队列

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;
	}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值