十四、LinkedBlockingQueue

一、概念

  • 底层是一个Node节点组成的一个单向链表
  • 基于ReentrantLock实现的,读写分离的阻塞队列,所以说LinkedBlockingQueue的吞吐量是要比ArrayBlockingQueue高的
  • 两把锁(ReentrantLock,只能是非公平的),一把读锁,一把写锁,所以说,读读互斥,写写互斥,读写不互斥
  • 其实这个的读写也用的是Condition,notEmpty控制读,notFull控制写
  • 可以用户自定义链表长度(所以严格意义来说,不是一个无界队列)

二、应用

写操作

  • add(E e)
    • 队列中添加数据,如果队列满了, 会抛出异常new IllegalStateException(“Queue full”)
      底层调用offer方法
    • 返回值boolean
  • offer(E e)
    • 队列中添加数据,如果队列满了,不会抛出异常,会返回false
    • 返回值boolean
  • offer(E e, long timeout, TimeUnit unit)
    • 队列中添加数据,如果队列满了,会阻塞当前线程timeout时间
    • 返回值boolean
  • put(E e)
    • 队列中添加数据,如果队列满了,会阻塞当前线程,直到有数据或者被打断
    • 无返回值

读操作

  • remove()
    • 获取队列中数据,如果队列中没有数据,则抛出异常throw new NoSuchElementException()
      底层调用poll方法
    • 返回值E
  • poll()
    • 获取队列中数据,如果队列中没有数据,则返回null
    • 返回值E
  • poll(long timeout, TimeUnit unit)
    • 获取队列中数据,如果队列中没有数据,则阻塞当前线程timeout时间
    • 返回值E
  • take()
    • 获取队列中数据,如果队列中没有数据,会阻塞当前线程,直到有数据
    • 返回值E

三、源码(jdk1.8)

重要属性

static class Node<E> {
    E item;
    Node<E> next;
    Node(E x) { item = x; }
}

// 容量,即链表长度
private final int capacity;

// 链表中实际数据数量,用Ato,就保证了读写的时候共享
private final AtomicInteger count = new AtomicInteger();

// 头节点
transient Node<E> head;

// 尾节点
private transient Node<E> last;

// 读锁,以及读用的Condition
private final ReentrantLock takeLock = new ReentrantLock();
private final Condition notEmpty = takeLock.newCondition();

// 写锁,以及写用的Condition
private final ReentrantLock putLock = new ReentrantLock();
private final Condition notFull = putLock.newCondition();

构造方法

public LinkedBlockingQueue() {
    this(Integer.MAX_VALUE);
}
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();
    }
}

offer(E e)

public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    // 拿到链表中的实际数据量
    final AtomicInteger count = this.count;
    // 如果实际数据量跟容量相等,则插入失败,返回false
    if (count.get() == capacity)
        return false;
    int c = -1;
    // 构建一个新的Node
    Node<E> node = new Node<E>(e);
    // 获取写锁
    final ReentrantLock putLock = this.putLock;
    putLock.lock();
    try {
        // 如果实际数据量小于容量,则插入
        if (count.get() < capacity) {
            // 插入链表
            enqueue(node);
            // 先将count赋值给c,然后再将count+1
            c = count.getAndIncrement();
            // 判断是不是还有容量,有的话,唤醒别的存放线程
            if (c + 1 < capacity)
                notFull.signal();
        }
    } finally {
        // 释放锁
        putLock.unlock();
    }
    // 如果C==0,那么就证明以前链表是个空的,可能会有读线程阻塞,则唤醒读线程
    if (c == 0)
        signalNotEmpty();
    return c >= 0;
}
private void enqueue(Node<E> node) {
    // 先将尾节点的next指向新节点,然后将last设置为新节点
    last = last.next = node;
}

add(E e)

public boolean add(E e) {
    if (offer(e))
        return true;
    else
        throw new IllegalStateException("Queue full");
}

offer(E e, long timeout, TimeUnit unit)

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

put(E e)

public void put(E e) throws InterruptedException {
    if (e == null) throw new NullPointerException();
    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();
}

poll()(E e)

public E poll() {
    // 获取当前链表的实际数据量
    final AtomicInteger count = this.count;
    // 如果count == 0, 则证明没有数据
    if (count.get() == 0)
        return null;
    E x = null;
    int c = -1;
    // 获取读锁
    final ReentrantLock takeLock = this.takeLock;
    takeLock.lock();
    try {
        // 如果count > 0,则证明有数据
        if (count.get() > 0) {
            // 获取数据
            x = dequeue();
            // 先拿到count的值赋给c,然后将count -1
            c = count.getAndDecrement();
            // 如果说c>1,则证明以前就有数据,唤醒阻塞的读线程
            if (c > 1)
                notEmpty.signal();
        }
    } finally {
        // 释放锁
        takeLock.unlock();
    }
    // 如果c==容量,则证明以前肯定是放满链表了,然后阻塞了哈,然后现在你已经拿走了一个,所以就唤醒阻塞的写线程
    if (c == capacity)
        signalNotFull();
    return x;
}
private E dequeue() {
    // 拿到head
    Node<E> h = head;
    // 将head的next拿到
    Node<E> first = h.next;
    // 然后将head的next指向自己,方便GC
    h.next = h; // help GC
    // 将head指向 head的next
    head = first;
    // 拿到first里面的值
    E x = first.item;
    // 将这个frist的item设置为null
    first.item = null;
    // 返回值
    return x;
}

remove()

public E remove() {
    E x = poll();
    if (x != null)
        return x;
    else
        throw new NoSuchElementException();
}

poll(long timeout, TimeUnit unit)

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

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

四、总结流程(个人总结,可能有误)

在这里插入图片描述

  • 千万不要有一个想法:如果读和写在同一个Node咋办
    • 这是不可能的,一定是写了一个Node,才会有读的线程去消费。看源码
    • 用一个Ato的count去控制的啊
  1. offer/put

    • offer:
      • 判断当前链表数据量跟容量是否相等
        • 相等,则证明满了,返回false
        • 不相等:
          • 获取写锁
          • 则将当前数据封装成Node,插入到链表尾端
          • 判断如果的count < 容量,则唤醒其他写线程
          • 释放写锁
          • 判断如果count == 0,则证明,以前有其他读线程在阻塞,则唤醒其他读线程
    • put:
      • 判断当前链表数量 == 0
        • 相等,则证明没有数据,返回null
        • 不相等:
          • 获取读锁
          • DCL判断当前链表数量 > 0,如果不是的话就直接返回null
          • 获取数据
          • 判断如果的count > 0,则唤醒其他读线程
          • 释放读锁
          • 判断如果count == 链表长度,则以前肯定是有些线程在阻塞,则唤醒其他写线程
  2. offer(E e, long timeout, TimeUnit unit)/poll(long timeout, TimeUnit unit)

    • offer(E e, long timeout, TimeUnit unit)
      • 获取写锁
      • 判断当前链表数据量跟容量是否相等
        • 相等,则Condition挂起线程timeout时间,等待被唤醒或者打断,然后执行不相等中的插入逻辑
        • 不相等:
          • 则将当前数据封装成Node,插入到链表尾端
          • 判断如果的count < 容量,则唤醒其他写线程
          • 释放写锁
          • 判断如果count == 0,则证明,以前有其他读线程在阻塞,则唤醒其他读线程
    • poll(long timeout, TimeUnit unit)
      • 获取读锁
      • 判断当前链表数量 == 0
        • 相等,则Condition挂起线程timeout时间,等待被唤醒或者打断,然后执行不相等中的获取逻辑
        • 不相等
          • 获取数据
          • 判断如果的count > 0,则唤醒其他读线程
          • 释放读锁
          • 判断如果count == 链表长度,则以前肯定是有些线程在阻塞,则唤醒其他写线程
  3. put(E e)/take()

    • put(E e)
      • 获取写锁
      • 判断当前链表数据量跟容量是否相等
        • 相等,则Condition挂起线程,等待被唤醒或者打断,然后执行不相等中的插入逻辑
        • 不相等:
          • 则将当前数据封装成Node,插入到链表尾端
          • 判断如果的count < 容量,则唤醒其他写线程
          • 释放写锁
          • 判断如果count == 0,则证明,以前有其他读线程在阻塞,则唤醒其他读线程
    • take()
      • 获取读锁
      • 判断当前链表数量 == 0
        • 相等,则Condition挂起线程,等待被唤醒或者打断,然后执行不相等中的获取逻辑
        • 不相等:
          • 获取数据
          • 判断如果的count > 0,则唤醒其他读线程
          • 释放读锁
          • 判断如果count == 链表长度,则以前肯定是有些线程在阻塞,则唤醒其他写线程
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值