michael nesterenko
michael nesterenko

Reputation: 14449

strange code in ThreadPoolExecutor$Worker

I have found such strange code in ThreadPoolExecutor$Worker.runTask

if (runState < STOP && Thread.interrupted() && runState >= STOP)
                thread.interrupt();

Why does it need to check runState < STOP and runState >= STOP. There is a comment that explains in some way why such double check is necessary but I dont understand it.

So to compute final value of expression it will take from memory runState, then call Thread.interrupted() and then again take from memory runState (the first runState may differ from the second?) and combine these three expression's values with and?

Upvotes: 3

Views: 330

Answers (1)

Sergey Aslanov
Sergey Aslanov

Reputation: 2415

Initial purpose of the code is to clear interrupted state of the thread unless it's shuttingDownNow, so it had to be just

if (runState < STOP)
      Thread.interrupted();

But we have concurrency. Consider two threads running code, Worker:

if (runState < STOP &&
      Thread.interrupted() &&
      runState >= STOP)
    thread.interrupt();

and thread executing shutdownNow:

if (state < STOP)
    runState = STOP;
for (Worker w : workers) {
    w.interruptNow();
}

Now here is the case for this double check

Worker:        if (runState < STOP &&    // true for now

shutdownNow:   if (state < STOP)
shutdownNow:       runState = STOP;      // set new state
shutdownNow:   for (Worker w : workers) {
shutdownNow:       w.interruptNow();     // interrupt      
shutdownNow:   }

Worker:              Thread.interrupted() &&   // clears interrupted state 
Worker:              runState >= STOP)         // but we have double check
Worker:            thread.interrupt();         // that will setup it again

Upvotes: 2

Related Questions