2013-04-13 57 views
0

在閱讀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(); 
    } 
} 

什麼行代碼的好處:最終ReentrantLock鎖= this.lock;

+0

@assylias。可能的重複 – fuyou001

回答

0

Doug Lea推廣了這個想法 - 我認爲最初的想法是當有一個最終的局部變量被使用時,JVM可能會執行一些性能相關的優化。

退房從OpenJDK的螺紋,其討論過這個問題this線程

編輯:

一個小小的研究扔了堆棧這兩個相關的問題:

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

Java Lock variable assignment before use. Why?

+0

這是最好的參考 - [這個其他線程](http://cs.oswego.edu/pipermail/concurrency-interest/2011-January/007703.html)是更多的信息。 – assylias

+0

謝謝 - 很好的鏈接 –