0

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

Looking at the implementation of java.util.concurrent.DelayQueue I see a pattern which I don't quite understand.

public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
implements BlockingQueue<E> {

private transient final ReentrantLock lock = new ReentrantLock();
private transient final Condition available = lock.newCondition();
private final PriorityQueue<E> q = new PriorityQueue<E>();

public boolean offer(E e) {
    **final ReentrantLock lock = this.lock;**//(*)
    lock.lock(); 
    try { ... }
    finally {lock.unlock();}

}

public E poll() {
    **final ReentrantLock lock = this.lock**;//(*)
    lock.lock(); 
    try { ... }
    finally {lock.unlock();}
 }}

What's the purpose of the (*) line (to work with temp reference to the field) which can be found in implementations of methods from the BlockingQueue interface where some concurrency (locks) is involved? Consider, that in the case the lock field is final and assigned during field intialization with other final fields.

Community
  • 1
  • 1
Andrey Taptunov
  • 9,367
  • 5
  • 31
  • 44

1 Answers1

1

Not copying the lock variable locally won't make any difference to the correctness of the code.

It is possible there's a very very small performance increase by doing this but I am unable to fathom why that would be. Other than that then it may be something the author considered a readability improvement.

Mike Q
  • 22,839
  • 20
  • 87
  • 129