Question

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();
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top