为什么读也要加锁?通过ArrayBlockingQueue源码进行分析

首先分析一下为什么写要加锁
以offer方法为例(增加元素)

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
	/** 存元素的数组 */
    final Object[] items;

    /** 删除,查询元素时,使用的下标 */
    int takeIndex;

    /** 添加元素时,使用的下标 */
    int putIndex;

    /** 元素总数 */
    int count;
    
    /** 锁 */
    final ReentrantLock lock;


	// 加元素的方法
    public boolean offer(E e) {
        checkNotNull(e);
        final ReentrantLock lock = this.lock;
        lock.lock(); //加锁
        try {
            if (count == items.length)
                return false;
            else {
                enqueue(e);  //核心是调用enqueue方法
                return true;
            }
        } finally {
            lock.unlock(); //解锁
        }
    }


     /**
        这个方法就是关键,里面有一行代码让putIndex自增
        这个操作不是原子的,为了防止出现两个线程++,结果仅仅加1的现象
        需要加锁
     **/
    private void enqueue(E x) {
        // assert lock.getHoldCount() == 1;
        // assert items[putIndex] == null;
        final Object[] items = this.items;
        items[putIndex] = x;
        if (++putIndex == items.length) //下标自增
            putIndex = 0;
        count++;
        notEmpty.signal();
    }


}

再来分析一下为什么读也要加锁
主要就是跟删除操作有关,我们来看一下删除操作&查询队首的源码
具体分析在注释中

public class ArrayBlockingQueue<E> extends AbstractQueue<E>
        implements BlockingQueue<E>, java.io.Serializable {
     //前面的不写了

    // 删元素的方法
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return (count == 0) ? null : dequeue(); //核心是调用dequeue方法
        } finally {
            lock.unlock();
        }
    }
    
    // 删除分为2步
    // 步骤1.删除takeIndex指向的元素
    // 步骤2.takeIndex指向后一个
    // 明白了这2步,就明白为什么查询队首的peek方法也需要加锁
    // 因为如果不加锁,万一在步骤1,2中间,别人来peek,就会拿到null
    private E dequeue() {
        // assert lock.getHoldCount() == 1;
        // assert items[takeIndex] != null;
        final Object[] items = this.items;
        @SuppressWarnings("unchecked")
        E x = (E) items[takeIndex];
        items[takeIndex] = null;   //步骤1
        if (++takeIndex == items.length)  //步骤2
            takeIndex = 0;
        count--;
        if (itrs != null)
            itrs.elementDequeued();
        notFull.signal();
        return x;
    }

	// 
    public E peek() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            return itemAt(takeIndex); // null when queue is empty
        } finally {
            lock.unlock();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值