Java 7之多线程并发容器 - LinkedBlockingQueue

LinkedBlockingQueue是一个单向链表实现的阻塞队列。该队列按 FIFO(先进先出)排序元素,新元素插入到队列的尾部,并且队列获取操作会获得位于队列头部的元素。链接队列的吞吐量通常要高于基于数组的队列,但是在大多数并发应用程序中,其可预知的性能要低。

此外,LinkedBlockingQueue还是可选容量的(防止过度膨胀),即可以指定队列的容量。如果不指定,默认容量大小等于Integer.MAX_VALUE。

看一下LinkedBlockingQueue类中定义的重要变量和Node节点,如下:

  1. // 链表的节点定义  
  2. static class Node<E> {  
  3.     E item;  
  4.     Node<E> next;  
  5.     Node(E x) { item = x; }  
  6. }  
  7.   
  8. private final int capacity;      // 链表的容量,可以在创建链表时指定  
  9. private final AtomicInteger count = new AtomicInteger(0);//  记录队列元素个数  
  10. private transient Node<E> head; // 链表的表头。取出数据时,都是从表头head处插入  
  11. private transient Node<E> last; // 链表的表尾。新增数据时,都是从表尾last处插入  
  12.   
  13. // putLock是插入锁,takeLock是取出锁;notEmpty是非空条件,notFull是未满条件。通过它们对链表进行并发控制  
  14. private final ReentrantLock takeLock = new ReentrantLock();  
  15. private final Condition notEmpty = takeLock.newCondition();  
  16.   
  17. private final ReentrantLock putLock = new ReentrantLock();  
  18. private final Condition notFull = putLock.newCondition();  
    // 链表的节点定义
    static class Node<E> {
        E item;
        Node<E> next;
        Node(E x) { item = x; }
    }

    private final int capacity;      // 链表的容量,可以在创建链表时指定
    private final AtomicInteger count = new AtomicInteger(0);//  记录队列元素个数
    private transient Node<E> head; // 链表的表头。取出数据时,都是从表头head处插入
    private transient Node<E> last; // 链表的表尾。新增数据时,都是从表尾last处插入

    // putLock是插入锁,takeLock是取出锁;notEmpty是非空条件,notFull是未满条件。通过它们对链表进行并发控制
    private final ReentrantLock takeLock = new ReentrantLock();
    private final Condition notEmpty = takeLock.newCondition();
    
    private final ReentrantLock putLock = new ReentrantLock();
    private final Condition notFull = putLock.newCondition();

看一下主要的两个构造函数,如下:

  1. public LinkedBlockingQueue(int capacity) {  
  2.        if (capacity <= 0throw new IllegalArgumentException();  
  3.        this.capacity = capacity;  
  4.        last = head = new Node<E>(null);  
  5.    }  
  6.   
  7.    public LinkedBlockingQueue(Collection<? extends E> c) {  
  8.        this(Integer.MAX_VALUE);  
  9.        final ReentrantLock putLock = this.putLock;  
  10.        putLock.lock(); // Never contended, but necessary for visibility  
  11.        try {  
  12.            int n = 0;  
  13.            for (E e : c) {  
  14.                if (e == null)  
  15.                    throw new NullPointerException();  
  16.                if (n == capacity)  
  17.                    throw new IllegalStateException("Queue full");  
  18.                enqueue(new Node<E>(e));  
  19.                ++n;  
  20.            }  
  21.            count.set(n);  
  22.        } finally {  
  23.            putLock.unlock();  
  24.        }  
  25.    }  
 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();
        }
    }
将c容器中的元素做为Node节点的值添加到链表中,如下:
  1. private void enqueue(Node<E> node) {  
  2.        // assert putLock.isHeldByCurrentThread();  
  3.        // assert last.next == null;  
  4.        last = last.next = node;  
  5.    }  
 private void enqueue(Node<E> node) {
        // assert putLock.isHeldByCurrentThread();
        // assert last.next == null;
        last = last.next = node;
    }

将node节点添加到last.next节点后面,并将last.next节点的值赋给last.


1、添加元素


  1. public void put(E e) throws InterruptedException {  
  2.        if (e == nullthrow new NullPointerException();  
  3.        // Note: convention in all put/take/etc is to preset local var  
  4.        // holding count negative to indicate failure unless set.  
  5.        int c = -1;  
  6.        Node<E> node = new Node(e);  
  7.        final ReentrantLock putLock = this.putLock;  
  8.        final AtomicInteger count = this.count;  
  9.        putLock.lockInterruptibly();  
  10.        try {  
  11.            /* 
  12.             * Note that count is used in wait guard even though it is 
  13.             * not protected by lock. This works because count can 
  14.             * only decrease at this point (all other puts are shut 
  15.             * out by lock), and we (or some other waiting put) are 
  16.             * signalled if it ever changes from capacity. Similarly 
  17.             * for all other uses of count in other wait guards. 
  18.             */  
  19.            while (count.get() == capacity) {  
  20.                notFull.await();  
  21.            }  
  22.            enqueue(node);  
  23.            c = count.getAndIncrement();  
  24.            if (c + 1 < capacity)  
  25.                notFull.signal();  
  26.        } finally {  
  27.            putLock.unlock();  
  28.        }  
  29.        if (c == 0)  
  30.            signalNotEmpty();  
  31.    }  
  32.   
  33.    /** 
  34.     * Inserts the specified element at the tail of this queue, waiting if 
  35.     * necessary up to the specified wait time for space to become available. 
  36.     */  
  37.    public boolean offer(E e, long timeout, TimeUnit unit)  
  38.        throws InterruptedException {  
  39.   
  40.        if (e == nullthrow new NullPointerException();  
  41.        long nanos = unit.toNanos(timeout);  
  42.        int c = -1;  
  43.        final ReentrantLock putLock = this.putLock;  
  44.        final AtomicInteger count = this.count;  
  45.        putLock.lockInterruptibly();  
  46.        try {  
  47.            while (count.get() == capacity) {  
  48.                if (nanos <= 0)  
  49.                    return false;  
  50.                nanos = notFull.awaitNanos(nanos);  
  51.            }  
  52.            enqueue(new Node<E>(e));  
  53.            c = count.getAndIncrement();  
  54.            if (c + 1 < capacity)  
  55.                notFull.signal();  
  56.        } finally {  
  57.            putLock.unlock();  
  58.        }  
  59.        if (c == 0)  
  60.            signalNotEmpty();  
  61.        return true;  
  62.    }  
  63.   
  64.    /** 
  65.     * Inserts the specified element at the tail of this queue if it is 
  66.     * possible to do so immediately without exceeding the queue's capacity, 
  67.     */  
  68.    public boolean offer(E e) {  
  69.        if (e == nullthrow new NullPointerException();  
  70.        final AtomicInteger count = this.count;  
  71.        if (count.get() == capacity)  
  72.            return false;  
  73.        int c = -1;  
  74.        Node<E> node = new Node(e);  
  75.        final ReentrantLock putLock = this.putLock;  
  76.        putLock.lock();  
  77.        try {  
  78.            if (count.get() < capacity) {  
  79.                enqueue(node);  
  80.                c = count.getAndIncrement();  
  81.                if (c + 1 < capacity)  
  82.                    notFull.signal();  
  83.            }  
  84.        } finally {  
  85.            putLock.unlock();  
  86.        }  
  87.        if (c == 0)  
  88.            signalNotEmpty();  
  89.        return c >= 0;  
  90.    }  
 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 {
            /*
             * Note that count is used in wait guard even though it is
             * not protected by lock. This works because count can
             * only decrease at this point (all other puts are shut
             * out by lock), and we (or some other waiting put) are
             * signalled if it ever changes from capacity. Similarly
             * for all other uses of count in other wait guards.
             */
            while (count.get() == capacity) {
                notFull.await();
            }
            enqueue(node);
            c = count.getAndIncrement();
            if (c + 1 < capacity)
                notFull.signal();
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
    }

    /**
     * Inserts the specified element at the tail of this queue, waiting if
     * necessary up to the specified wait time for space to become available.
     */
    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;
    }

    /**
     * Inserts the specified element at the tail of this queue if it is
     * possible to do so immediately without exceeding the queue's capacity,
     */
    public boolean offer(E e) {
        if (e == null) throw new NullPointerException();
        final AtomicInteger count = this.count;
        if (count.get() == capacity)
            return false;
        int c = -1;
        Node<E> node = new Node(e);
        final ReentrantLock putLock = this.putLock;
        putLock.lock();
        try {
            if (count.get() < capacity) {
                enqueue(node);
                c = count.getAndIncrement();
                if (c + 1 < capacity)
                    notFull.signal();
            }
        } finally {
            putLock.unlock();
        }
        if (c == 0)
            signalNotEmpty();
        return c >= 0;
    }


2、删除元素


  1. public boolean remove(Object o) {  
  2.      if (o == nullreturn false;  
  3.      fullyLock();  
  4.      try {  
  5.          for (Node<E> trail = head, p = trail.next;  
  6.               p != null;  
  7.               trail = p, p = p.next) {  
  8.              if (o.equals(p.item)) {  
  9.                  unlink(p, trail);  
  10.                  return true;  
  11.              }  
  12.          }  
  13.          return false;  
  14.      } finally {  
  15.          fullyUnlock();  
  16.      }  
  17.  }  
  18.  public E take() throws InterruptedException {  
  19.      E x;  
  20.      int c = -1;  
  21.      final AtomicInteger count = this.count;  
  22.      final ReentrantLock takeLock = this.takeLock;  
  23.      takeLock.lockInterruptibly();  
  24.      try {  
  25.          while (count.get() == 0) {  
  26.              notEmpty.await();  
  27.          }  
  28.          x = dequeue();  
  29.          c = count.getAndDecrement();  
  30.          if (c > 1)  
  31.              notEmpty.signal();  
  32.      } finally {  
  33.          takeLock.unlock();  
  34.      }  
  35.      if (c == capacity)  
  36.          signalNotFull();  
  37.      return x;  
  38.  }  
  39.   
  40.  public E poll(long timeout, TimeUnit unit) throws InterruptedException {  
  41.      E x = null;  
  42.      int c = -1;  
  43.      long nanos = unit.toNanos(timeout);  
  44.      final AtomicInteger count = this.count;  
  45.      final ReentrantLock takeLock = this.takeLock;  
  46.      takeLock.lockInterruptibly();  
  47.      try {  
  48.          while (count.get() == 0) {  
  49.              if (nanos <= 0)  
  50.                  return null;  
  51.              nanos = notEmpty.awaitNanos(nanos);  
  52.          }  
  53.          x = dequeue();  
  54.          c = count.getAndDecrement();  
  55.          if (c > 1)  
  56.              notEmpty.signal();  
  57.      } finally {  
  58.          takeLock.unlock();  
  59.      }  
  60.      if (c == capacity)  
  61.          signalNotFull();  
  62.      return x;  
  63.  }  
  64.   
  65.  public E poll() {  
  66.      final AtomicInteger count = this.count;  
  67.      if (count.get() == 0)  
  68.          return null;  
  69.      E x = null;  
  70.      int c = -1;  
  71.      final ReentrantLock takeLock = this.takeLock;  
  72.      takeLock.lock();  
  73.      try {  
  74.          if (count.get() > 0) {  
  75.              x = dequeue();  
  76.              c = count.getAndDecrement();  
  77.              if (c > 1)  
  78.                  notEmpty.signal();  
  79.          }  
  80.      } finally {  
  81.          takeLock.unlock();  
  82.      }  
  83.      if (c == capacity)  
  84.          signalNotFull();  
  85.      return x;  
  86.  }  
   public boolean remove(Object o) {
        if (o == null) return false;
        fullyLock();
        try {
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (o.equals(p.item)) {
                    unlink(p, trail);
                    return true;
                }
            }
            return false;
        } finally {
            fullyUnlock();
        }
    }
    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;
    }

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

    public E poll() {
        final AtomicInteger count = this.count;
        if (count.get() == 0)
            return null;
        E x = null;
        int c = -1;
        final ReentrantLock takeLock = this.takeLock;
        takeLock.lock();
        try {
            if (count.get() > 0) {
                x = dequeue();
                c = count.getAndDecrement();
                if (c > 1)
                    notEmpty.signal();
            }
        } finally {
            takeLock.unlock();
        }
        if (c == capacity)
            signalNotFull();
        return x;
    }


3、删除元素


  1. public E peek() {  
  2.         if (count.get() == 0)  
  3.             return null;  
  4.         final ReentrantLock takeLock = this.takeLock;  
  5.         takeLock.lock();  
  6.         try {  
  7.             Node<E> first = head.next;  
  8.             if (first == null)  
  9.                 return null;  
  10.             else  
  11.                 return first.item;  
  12.         } finally {  
  13.             takeLock.unlock();  
  14.         }  
  15.     }  
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();
        }
    }


4、迭代元素

  1. public Iterator<E> iterator() {  
  2.   return new Itr();  
  3. }  
public Iterator<E> iterator() {
  return new Itr();
}

  1. private class Itr implements Iterator<E> {  
  2.     // 当前节点  
  3.     private Node<E> current;  
  4.     // 上一次返回的节点  
  5.     private Node<E> lastRet;  
  6.     // 当前节点对应的值  
  7.     private E currentElement;  
  8.   
  9.     Itr() {  
  10.         // 同时获取“插入锁putLock” 和 “取出锁takeLock”  
  11.         fullyLock();  
  12.         try {  
  13.             // 设置“当前元素”为“队列表头的下一节点”,即为队列的第一个有效节点  
  14.             current = head.next;  
  15.             if (current != null)  
  16.                 currentElement = current.item;  
  17.         } finally {  
  18.             // 释放“插入锁putLock” 和 “取出锁takeLock”  
  19.             fullyUnlock();  
  20.         }  
  21.     }  
  22.   
  23.     // 返回“下一个节点是否为null”  
  24.     public boolean hasNext() {  
  25.         return current != null;  
  26.     }  
  27.   
  28.     private Node<E> nextNode(Node<E> p) {  
  29.         for (;;) {  
  30.             Node<E> s = p.next;  
  31.             if (s == p)  
  32.                 return head.next;  
  33.             if (s == null || s.item != null)  
  34.                 return s;  
  35.             p = s;  
  36.         }  
  37.     }  
  38.   
  39.     // 返回下一个节点  
  40.     public E next() {  
  41.         fullyLock();  
  42.         try {  
  43.             if (current == null)  
  44.                 throw new NoSuchElementException();  
  45.             E x = currentElement;  
  46.             lastRet = current;  
  47.             current = nextNode(current);  
  48.             currentElement = (current == null) ? null : current.item;  
  49.             return x;  
  50.         } finally {  
  51.             fullyUnlock();  
  52.         }  
  53.     }  
  54.   
  55.     // 删除下一个节点  
  56.     public void remove() {  
  57.         if (lastRet == null)  
  58.             throw new IllegalStateException();  
  59.         fullyLock();  
  60.         try {  
  61.             Node<E> node = lastRet;  
  62.             lastRet = null;  
  63.             for (Node<E> trail = head, p = trail.next;  
  64.                  p != null;  
  65.                  trail = p, p = p.next) {  
  66.                 if (p == node) {  
  67.                     unlink(p, trail);  
  68.                     break;  
  69.                 }  
  70.             }  
  71.         } finally {  
  72.             fullyUnlock();  
  73.         }  
  74.     }  
  75. }  
private class Itr implements Iterator<E> {
    // 当前节点
    private Node<E> current;
    // 上一次返回的节点
    private Node<E> lastRet;
    // 当前节点对应的值
    private E currentElement;

    Itr() {
        // 同时获取“插入锁putLock” 和 “取出锁takeLock”
        fullyLock();
        try {
            // 设置“当前元素”为“队列表头的下一节点”,即为队列的第一个有效节点
            current = head.next;
            if (current != null)
                currentElement = current.item;
        } finally {
            // 释放“插入锁putLock” 和 “取出锁takeLock”
            fullyUnlock();
        }
    }

    // 返回“下一个节点是否为null”
    public boolean hasNext() {
        return current != null;
    }

    private Node<E> nextNode(Node<E> p) {
        for (;;) {
            Node<E> s = p.next;
            if (s == p)
                return head.next;
            if (s == null || s.item != null)
                return s;
            p = s;
        }
    }

    // 返回下一个节点
    public E next() {
        fullyLock();
        try {
            if (current == null)
                throw new NoSuchElementException();
            E x = currentElement;
            lastRet = current;
            current = nextNode(current);
            currentElement = (current == null) ? null : current.item;
            return x;
        } finally {
            fullyUnlock();
        }
    }

    // 删除下一个节点
    public void remove() {
        if (lastRet == null)
            throw new IllegalStateException();
        fullyLock();
        try {
            Node<E> node = lastRet;
            lastRet = null;
            for (Node<E> trail = head, p = trail.next;
                 p != null;
                 trail = p, p = p.next) {
                if (p == node) {
                    unlink(p, trail);
                    break;
                }
            }
        } finally {
            fullyUnlock();
        }
    }
}


转载自http://blog.youkuaiyun.com/mazhimazh/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值