سؤال

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();
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top