2016-09-15 52 views
2

在ArrayBlockingQueue實現中,爲什麼不直接訪問全局變量?ArrayBlockingQueue:爲什麼不直接訪問全局變量?

public class ArrayBlockingQueue<E> extends AbstractQueue<E> 
      implements BlockingQueue<E>, java.io.Serializable { 

    /** The queued items */ 
    final Object[] items; 

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

    // ... 

    public ArrayBlockingQueue(int capacity, boolean fair) { 
     if (capacity <= 0) 
      throw new IllegalArgumentException(); 
     this.items = new Object[capacity]; 
     lock = new ReentrantLock(fair); 
     // ... 
    } 

    @Override 
    public E poll() { 
     final ReentrantLock lock = this.lock; // Why the global variable assigned to a local variable ? 
     lock.lock(); 
     try { 
      return (count == 0) ? null : extract(); 
     } finally { 
      lock.unlock(); 
     } 
    } 

} 

poll方法中,全局的ReentrantLock lock變量被分配給一個局部變量和它的參考使用。爲什麼如此?

回答

0

局部變量存儲在堆棧中,訪問速度更快。

+0

這不是網站尋找的答案,這是最好的評論,也是最差的。 –