While studying the source code, I came across the following passage:

#JDK 8, java.util.concurrent.ThreadPoolExecutor 1120:1137 final void runWorker(Worker w) { Thread wt = Thread.currentThread(); Runnable task = w.firstTask; w.firstTask = null; w.unlock(); // allow interrupts boolean completedAbruptly = true; try { while (task != null || (task = getTask()) != null) { w.lock(); // If pool is stopping, ensure thread is interrupted; // if not, ensure thread is not interrupted. This // requires a recheck in second case to deal with // shutdownNow race while clearing interrupt if ((runStateAtLeast(ctl.get(), STOP) || (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP))) && !wt.isInterrupted()) wt.interrupt(); 

As far as I understand, instead of Thread.interrupted() worth calling wt.interrupted() - just for reasons of code uniformity (the implementation itself would not change it). Am I right, or is this some kind of feature that I overlooked?

upd. in the primary edition - left unchanged above - I made a mistake on my head, the alternative is to call wt.isInterrupted(true)

  • four
    Thread.interrupted() is a static method. Static methods are not accepted to be called on a class instance. - a_gura

1 answer 1

In your particular case, there will be no difference, wt is the current stream. But in order not to force the reader to think, “is the wt current stream?”, It is better to call the static method in a static way.


Explanation:

As already correctly noted, interrupted is a static method that is called on the current thread.

If you have t - Thread that is not current, and you call t.interrupted() , then a static method will be called, which, of course, will tell you the state of the thread interruption flag not for t , but for the current thread! This can lead to quite unpleasant errors.

  • That's what strains me, that with the flow in all cases, except for one, they interact directly. Since the stream is already working not as with the current one, then why complicate readability? - etki
  • @Etki: The question essentially needs to be addressed to the developers of the runtime library. Why did they make a static method, I'll never know. But since the static method is, calling it through the instance is worse than violating readability. Because readability plays against intuition in this case. - VladD
  • The static method is actually just a wrapper over a non-static one. But I’ve been a little confused with writing an alternate path, probably calling it simply because the alternate path involves a call with arguments, and is indeed a more acceptable API. The problem is in the signature rather than in static / non-static - etki
  • @Etki: Well. there still is the isInterrupted instance method, but it does not reset the internal flag. A static resets. Incomprehensible zoo almost identical methods. API authors smoked something unkind. - VladD
  • Oh, I did not notice that it is private. The question is finally removed. - etki