开发者

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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜