ArrayBlockingQueue 方法里锁赋值给一个本地 final 变量

【ArrayBlockingQueue 方法里锁赋值给一个本地 final 变量】

public class ArrayBlockingQueue<E> {

    /** Main lock guarding all access */
    final ReentrantLock lock;

    public E take() throws InterruptedException {
        // 就是下面这行,为什么要把 this.lock 赋值给一个本地 final 变量
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            while (count == 0)
                notEmpty.await();
            return dequeue();
        } finally {
            lock.unlock();
        }
    }
}

It’s an extreme optimization Doug Lea, the author of the class, likes to use. Here’s a post on a recent thread on the core-libs-dev mailing list about this exact subject which answers your question pretty well.

stackoverflow - arrayblockingqueue-why-copy-final-memever-field-into-local-final-variable

It’s a coding style made popular by Doug Lea.
It’s an extreme optimization that probably isn’t necessary;
you can expect the JIT to make the same optimizations.
(you can try to check the machine code yourself!)
Nevertheless, copying to locals produces the smallest
bytecode, and for low-level code it’s nice to write code
that’s a little closer to the machine.

Also, optimizations of finals (can cache even across volatile
reads) could be better. John Rose is working on that.

For some algorithms in j.u.c,
copying to a local is necessary for correctness.

Performance of locally copied members ?

极致优化,让编译器(本地编译器或者 JIT)更有可能把后续对堆上同一个地址的访问"优化"成对栈上比较近的地址或寄存器的访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lixifun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值