BlockQueue之LinkedBlockingQueue源码解析

     最近在研究blockqueue的源码,从今天开始,和大家分享一下我看源码的一些心得体会

     (1)LinkedBlockingQueue源码解析

     (2)ArrayBlockingQueue源码解析

    

     LinkedBlockingQueue实现了BlockingQueue接口以及Serializable接口,是有序的FIFO队列,构造函数中,可传入一个最大容量值,如果没有传入,则默认是Integer.MAX_VALUE

    一 首先看一下重要的几个类变量:

/** 保存当前队列中元素的个数 */
    private final AtomicInteger count = new AtomicInteger(0);

    /**
     * 头元素
     * Invariant: head.item == null
     */
    private transient Node<E> head;

    /**
     * 尾元素
     * Invariant: last.next == null
     */
    private transient Node<E> last;

    /** 消费者锁,Lock held by take, poll, etc */
    private final ReentrantLock takeLock = new ReentrantLock();

    /** 使消费者线程等待,直到被唤醒或者打断 */
    private final Condition notEmpty = takeLock.newCondition();

    /** 生产者锁,Lock held by put, offer, etc */
    private final ReentrantLock putLock = new ReentrantLock();

    /** 使生产者线程等待,直到被唤醒或者打断 */
    private final Condition notFull = putLock.newCondition();

 

二 put方法

public void put(E e) throws InterruptedException {
        if (e == null) throw new NullPointerException();
        // Note: convention in all put/take/etc is to preset local var
        // holding count negative to indicate failure unless set.
        int c = -1;
        Node<E> node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
              while (count.get() == capacity) {
                notFull.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

   

执行过程如下:

   1 如果传入元素为空,抛出空指针异常

   2 获得put的锁,以及原子的count,然后lock,注意,是可打断的lock
   3 判断当前队列是否饱和,若饱和,生产者线程进入等待状态
   4 如果队列不饱和,则将元素包装为一个node放到队列中
   5 count+1,如果count+1仍然小于队列的最大容量,则生产者线程被唤醒
   6 在finnally中释放锁,最后唤醒消费者,提醒消费者可以从队列中取对象了
 
三 offer方法
   offer提供了两个方法,一个方法是可传入等待时间,另一个则没有
 
   
public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException {

        if (e == null) throw new NullPointerException();
        long nanos = unit.toNanos(timeout);
        int c = -1;
        final ReentrantLock putLock = this.putLock;
        final AtomicInteger count = this.count;
        putLock.lockInterruptibly();
        try {
            while (count.get() == capacity) {
                if (nanos <= 0)
                    return false;
                nanos = notFull.awaitNanos(nanos);
            }
            enqueue(new Node<E>(e));
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return true;
    }
 
执行过程如下:
1 如果传入元素为空,抛出空指针异常
2 根据传入的timeout和unit计算出最长等待的时间
获得put的锁,以及原子的count,表示当前队列中的元素个数,然后lock,注意,是可打断的lock
4 如果队列饱和,则超过等待时间后,直接返回false
5 以下处理构成同put
 
另外一个不带参数的方法,如果判断队列饱和,直接返回false,不阻塞
 
四 take方法
 
 
public E take() throws InterruptedException {
        E x;
        int c = -1;
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                notEmpty.await();
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }
 
执行过程如下:
获得put的锁,以及原子的count,表示当前队列中的元素个数,然后lock,注意,是可打断的lock
2 如果当前队列为空,则阻塞
3 如果非空,则元素出列,count-1,如果count>1,表示队列非空,则消费者线程被唤醒
4 在finally中释放lock,唤醒生产者生产

五 pool方法

public E poll(long timeout, TimeUnit unit) throws InterruptedException {
        E x = null;
        int c = -1;
        long nanos = unit.toNanos(timeout);
        final AtomicInteger count = this.count;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lockInterruptibly();
        try {
            while (count.get() == 0) {
                if (nanos <= 0)
                    return null;
                nanos = notEmpty.awaitNanos(nanos);
            }
            x = dequeue();
            c = count.getAndDecrement();
            if (c > 1)
                notEmpty.signal();
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }

 

执行过程如下:

1   获得put的锁,以及原子的count,表示当前队列中的元素个数,然后lock,注意,是可打断的lock
2 如果当前队列为空,则线程阻塞,并等待指定时间,如果在指定时间还是空,则直接返回空
3 以下过程同take
 
pool也提供了不带参数的方法,表示如果队列为空,则直接返回null,不阻塞
 
六 peek
 
public E peek() {
        if (count.get() == 0)
            return null;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            Node<E> first = head.next;
            if (first == null)
                return null;
            else
                return first.item;
        } finally {
            takeLock.unlock();
        }
    }
 
不阻塞,不移除队首元素
 
根据以上源码分析,得出方法之间的异同:
(1) 生产者方法:put,offer
(2)消费者方法:take,poll,peek
(3)put方法中,如果队列始终饱和,则当前线程会一直等待,直到有对象出列
     offer(可传入等待时间),如果队列饱满,会等待指定的时间,如果在指定时间内还饱满,则直接返回false
     offer(没有参数),如果队列饱满,直接返回false,线程不等待
     put和 offer(可传入等待时间)都是可被打断的

 (4)take在队列为空时,会始终阻塞

          poll分为带等待时间和不带的,如果不带等待时间,则不阻塞,移除队首元素(FIFO)
          peek是不移除队首元素,不阻塞

猜你喜欢

转载自wang7839186.iteye.com/blog/2294376