6

In java JRE I saw the code

private final ReentrantLock lock;
public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();

Why is lock captured to a private variable? I would expect simply

public E poll() {
        lock.lock();
Sam DeHaan
  • 10,246
  • 2
  • 40
  • 48
mikebloch
  • 1,577
  • 11
  • 21
  • 5
    Duplicate of http://stackoverflow.com/questions/2785964/in-arrayblockingqueue-why-copy-final-member-field-into-local-final-variable – Skip Head Apr 16 '12 at 19:54

1 Answers1

0

Primarily it is to ensure maximum performance. Although this is a real micro-optimisation, it's probably in performance-sensitive code, and you might as well make it.

You also need to be very careful that the lock reference you are using doesn't mutate. Sure make the field final, but taking a final local reference is locally explicit.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
  • What does it optimize? is accessing a final class member slower than a local final member? – Eugene Retunsky Apr 16 '12 at 19:54
  • 1
    @EugeneRetunsky if you look at the duplicate post and what it quotes: "copying to locals produces the smallest bytecode" – trutheality Apr 16 '12 at 20:00
  • Yes, but this is really microscopic. And from the performance point you won't notice that - even at nanoseconds level, I believe. Especially comparing to locking/unlocking. Also, it saves only ONE access to the field and makes code less clear with non-noticeable result in performance. – Eugene Retunsky Apr 16 '12 at 20:29
  • 2
    Well, it's not that simple -- it could save you a whole cache miss, or even a page fault. The reasons to do it outweigh the reasons not to do it. – Marko Topolnik Apr 16 '12 at 21:13
  • 2
    I believe the performance was measured. Doug's like that. Also bytecode size affects whether HotSpot inlines. – Tom Hawtin - tackline Apr 16 '12 at 23:01