2

In the ArrayBlockingQueue Implementation, Why the global variables are not accessed directly ?

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

}   

In the poll method, the global ReentrantLock lock variable is assigned to a local variable and it's reference is used. Why it so?

Kamal Chandraprakash
  • 1,872
  • 18
  • 28

1 Answers1

0

Local variables are stored on the stack and accessed faster.

Sergey Bespalov
  • 1,746
  • 1
  • 12
  • 29
  • this is not the kind of answers the site is looking for, this is a comment at best and a poor one at that. –  Sep 16 '16 at 08:28