7

For example, here is a code snippet from java.util.concurrent.ThreadPoolExecutor:

public long getTaskCount() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        long n = completedTaskCount;
        for (Worker w : workers) {
            n += w.completedTasks;
            if (w.isLocked())
                ++n;
        }
        return n + workQueue.size();
    } finally {
        mainLock.unlock();
    }
}

In this snippet, the local variable mainLock is created to reference this.mainLock, but in my opinion, this is unnecessary, I would just use this.mainLock directly.

Actually, other cases of the same style have been observed in HashMap source codes and some other places. So what I'm wondering is what purpose of this code style is. Thanks!

Silent
  • 171
  • 1
  • 3

0 Answers0