LinkedBlockingQueue

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

 

Introduction

LinkedBlockingQueue implementation of the BlockingQueue interface

Location: JDK java.util.concurrent package, the package and the LinkedBlockingQueue itself, also realize the concurrent processing, using the access lock mode

The following cut directly into the source code

Constructor

 

The default constructor with no parameters

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);//The default length
}

Specifies the length of the constructor

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

 

Storage method

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();//Put lock
    try {
        while (count.get() == capacity) {//Judge whether the queue is full. If the queue is full, have been waiting for
            notFull.await();
        }
        enqueue(node);//In the queue tail
        c = count.getAndIncrement();//Increment the counter
        if (c + 1 <capacity)
            notFull.signal();
    } finally {
        putLock.unlock();//The release of the put lock
    }
    if (c == 0)
        signalNotEmpty();
}

 

Methods

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) {//To judge whether the queue is empty. If NULL is always circular wait
            notEmpty.await();
        }
        x = dequeue();//Remove the head of the queue
        c = count.getAndDecrement();//Counter decrement
        if (c > 1)
            notEmpty.signal();
    } finally {
        takeLock.unlock();//The release of the tack lock
    }
    if (c == capacity)
        signalNotFull();
    return x;
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Stanley at December 23, 2013 - 6:29 AM