关于java:BlockingQueue-LinkedBlockingQueue

LinkedBlockingQueue是一个能够有界、也能够无界的阻塞队列,以FIFO(先进先出)的形式拜访队列。

head是队首节点,是进入队列工夫最长的节点,tail是队尾节点,是进入队列工夫最短的节点。

节点从队尾退出队列,从head出队。

LinkedBlockingQueue#次要属性

节点:通过外部类Node定义节点:

static class Node<E> {
        E item;
        Node<E> next;

        Node(E x) { item = x; }
    }

很简略,次要属性就两个:
next:下一节点。
item:节点蕴含的数据。

capacity:队列容量,无界队列值为Integer.MAX_VALUE。

count:队列以后节点数,AtomicInteger类型。

head:头节点。

last:尾结点。

takeLock:ReentrantLock,出队锁,也就是从队列获取数据的锁。

notEmpty:takeLock的Condition,帮助获取数据的线程排队。

putLock:ReentrantLock,入队锁,数据退出队列的锁。

notFull:putLock的Condition,帮助退出队列的线程排队。

构造方法

无参构造方法创立一个无边界空队列。

public LinkedBlockingQueue() {
        this(Integer.MAX_VALUE);
    }

带容量参数capacity的构造方法创立一个有界空队列

   public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

汇合参数结构器创立一个无界队列,将参数的汇合初始化到队列中:

public LinkedBlockingQueue(Collection<? extends E> c) {
        this(Integer.MAX_VALUE);
        final ReentrantLock putLock = this.putLock;
        putLock.lock(); // Never contended, but necessary for visibility
        try {
            int n = 0;
            for (E e : c) {
                if (e == null)
                    throw new NullPointerException();
                if (n == capacity)
                    throw new IllegalStateException("Queue full");
                enqueue(new Node<E>(e));
                ++n;
            }
            count.set(n);
        } finally {
            putLock.unlock();
        }
    }

须要留神创立的队列中必然会蕴含一个dummy性质的head节点,所以出队列的时候这个head节点必定也须要跳过。

put办法

元素退出队列的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>(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();
    }

首先创立Node,并尝试通过putLock.lockInterruptibly();为以后线程获取对队列的写入锁。如果获取到则会立刻返回,否则以后线程阻塞期待。

拿到写入锁之后,判断如果以后队列已达容量上线(count.get() == capacity)的话,在notFull上阻塞期待。

否则,如果容量未满或者其余出队线程(从队列take数据的线程胜利拿走数据之后)释放出来队列容量后唤醒以后线程后,以后节点enqueue(node)退出队列尾部。而后累加以后队列容量count,并判断如果容量未满的话,唤醒在notFull上期待容量的其余过程。

之后开释putLock锁。

最初,如果退出的节点是队列的第一个节点(c==0,空队列退出),这种状况下可能会有期待take数据的线程在阻塞期待,所以调用signalNotEmpty()唤醒阻塞的take线程。

take办法

获取数据的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;
    }

首先获取takeLock,获取不到则阻塞期待,获取到则立刻返回。

拿到take锁之后,判断如果以后队列是空队列(count.get() == 0)的话,在notEmpty上阻塞期待。

否则,如果队列不空或者其余写入线程(参考put办法,put实现之后唤醒take阻塞线程)写入队列后唤醒以后线程后,调用dequeue办法获取数据。而后从新计算(减)以后队列容量count,并判断如果队列不空的话,唤醒在notEmpty上期待数据的其余take过程。

之后开释takeLock锁。

最初,如果take之前队列已满(c == capacity),这种状况下可能会有期待put数据的线程在阻塞期待,signalNotFull()唤醒阻塞的put线程。

最初将通过dequeue()办法取出的数据返回。

dequeue()办法

去head的次节点,获取该节点的item返回,之后头节点移出队列,次节点变成头节点,并且将变成头节点的次节点(此时其数据item曾经被获取到)item置空。

private E dequeue() {
        // assert takeLock.isHeldByCurrentThread();
        // assert head.item == null;
        Node<E> h = head;
        Node<E> first = h.next;
        h.next = h; // help GC
        head = first;
        E x = first.item;
        first.item = null;
        return x;
    }

从出队办法dequeue()咱们须要明确以下两点:

  1. 数据是从次节点(头节点的next节点)获取到的,因为头节点是dummy节点
  2. 头节点移出队列,次节点清理变为dummy节点之后,再变为头节点(怯懦的站在头部装B)

小结

比SynchronousQueue的源码简略多了。不过咱们只剖析了他的两个次要办法,对于汇合类的其余办法,LinkedBlockingQueue也是反对的,代码逻辑也都绝对比较简单,须要留神某些操作比方remove、contains等是须要同时获取putLock和takeLock的。其余的写入办法比方offer、数据获取办法比方poll,代码逻辑和put、take大同小异,很容易了解。

只不过阻塞队列LinkedBlockingQueue也是提供非阻塞办法的,比方poll、offer,如果offer的时候队列已满、或者poll的时候空队列,则立刻返回false。

对代码了解有妨碍的中央应该是ReentrantLock和Condition,是了解LinkedBlockingQueue源码的前提。

Thanks a lot!

上一篇 BlockingQueue – 基于TransferQueue的SynchronousQueue

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理