1

I've been reading Java's source code regarding Executors services. Upon inspecting ThreadPoolExecutor class I've found this code for shutdown:

public void shutdown() {
    final ReentrantLock mainLock = this.mainLock;
    mainLock.lock();
    try {
        checkShutdownAccess();
        advanceRunState(SHUTDOWN);
        interruptIdleWorkers();
        onShutdown(); // hook for ScheduledThreadPoolExecutor
    } finally {
        mainLock.unlock();
    }
    tryTerminate();
}

And I don't understand what's the point of this lock being local to the method. If my understanding is right new lock is created for every call to this function which kinda makes this lock redundant (as in thread calling always passes the locking) and it is not visible anywhere outside methods scope.

This coding pattern repeats throughout the class, with declaring local final lock, locking and then unlocking it.

EDIT:

  • fixed code misreading nonsense
nmiculinic
  • 2,224
  • 3
  • 24
  • 39
  • From the answer to the duplicate: "*this idiom has to do with CPU caches as reading from a stack location is more cache-friendly than reading from a random heap location. There is also a higher chance that the local var will end up bound to a CPU register.*" – assylias Dec 08 '15 at 10:53

2 Answers2

2

The final modifier is just for the reference created inside the method. It is still referring to the actual lock created at the class/object level. So just to clarify, no new lock is created for each method call; it uses the existing lock from the object (this).

I'm assuming the objects of this classes are shared across multiple threads and hence the need for this sort of pattern.

Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • I think there are two points here: why create a local copy when you can just do `this.lock` and why have a lock for the `shutDown` methods. The first point is already explained by the comments and linked threads. For the second part, the locking is done to ensure you don't end up calling `shutDown` when another shutdown is already in progress hence the pattern. – Sanjay T. Sharma Dec 08 '15 at 11:00
1

It is supposed to encourage the compiler and the JVM to do the right thing during optimisation.

See Instructions reordering in Java JVM for more discussion on what the optimiser can do.

Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213