【问题标题】:what's the benefit of the code [duplicate]代码有什么好处[重复]
【发布时间】:2013-04-13 13:30:55
【问题描述】:

在阅读 ArrayBlockingQueue 的源代码时,我发现以下代码:

public E take() throws InterruptedException {
    final ReentrantLock lock = this.lock;
    lock.lockInterruptibly();
    try {
        try {
            while (count == 0)
                notEmpty.await();
        } catch (InterruptedException ie) {
            notEmpty.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        E x = extract();
        return x;
    } finally {
        lock.unlock();
    }
}

为什么不使用代码

public E take() throws InterruptedException {
     lock.lockInterruptibly();
    try {
        try {
            while (count == 0)
                notEmpty.await();
        } catch (InterruptedException ie) {
            notEmpty.signal(); // propagate to non-interrupted thread
            throw ie;
        }
        E x = extract();
        return x;
    } finally {
        lock.unlock();
    }
}

行代码有什么好处:final ReentrantLock lock = this.lock;

【问题讨论】:

  • @assylias .可能重复

标签: concurrency locking java


【解决方案1】:

Doug Lea 推广了这个想法——我认为最初的想法是当使用 final 局部变量时,JVM 可能会执行一些与性能相关的优化。

从讨论这个问题的 OpenJDK 线程中查看 this 线程

编辑:

一点研究在堆栈上抛出了这两个相关的问题:

In ArrayBlockingQueue, why copy final member field into local final variable?

Java Lock variable assignment before use. Why?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-13
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2013-06-01
相关资源
最近更新 更多