Recently I am puzzled with Java multi-threading programming and I tried to refer some open-source code. I read Android's LinkedBlockingQueue
, and the implementation of the put
method really confuses me.
public void put(E e) throws InterruptedException {
if (e == null) throw new NullPointerException();
int c = -1;
Node<E> node = new Node<E>(e);
final ReentrantLock putLock = this.putLock; // #1
final AtomicInteger count = this.count; // #2
putLock.lockInterruptibly();
try {
// ...
while (count.get() == capacity) {
notFull.await();
}
enqueue(node);
c = count.getAndIncrement();
if (c + 1 < capacity)
notFull.signal();
} finally {
putLock.unlock();
}
if (c == 0)
signalNotEmpty();
}
It seems that in many multi-thread programming in java, it is common that using final local variables
to get a reference to a class member(#1 and #2 here as an example).
But I don't understand why programmers use this trick. In this example, what if I use this.putLock
to call lockInterruptibly
directly rather than call lockInterruptibly
after assigning it to a local variable? What's the difference between them?