Why is lock captured to a local variable
Asked Answered
S

1

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();
Shimmy answered 16/4, 2012 at 19:49 Comment(1)
Duplicate of #2786464Derbyshire
H
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.

Henka answered 16/4, 2012 at 19:52 Comment(5)
What does it optimize? is accessing a final class member slower than a local final member?Fibroblast
@EugeneRetunsky if you look at the duplicate post and what it quotes: "copying to locals produces the smallest bytecode"Krupp
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.Fibroblast
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.Recycle
I believe the performance was measured. Doug's like that. Also bytecode size affects whether HotSpot inlines.Henka

© 2022 - 2024 — McMap. All rights reserved.