0

I have code, which needs to wait a while as a part of busy-wait (due to legacy code I cannot change that much). I've read the reasoning why I should do that here [1] and [2], and it's presented as no-brainer rule of thumb. Do this always. IIUC it's sold as necessary because some code higher up call stack can be doing things like:

while (!Thread.currentThread().isInterrupted()) {

and without calling

Thread.currentThread().interrupt()

or rethrowing it would fail.

Now back to my case. I called minuscule method sleep. If I was woken up in the middle of busy wait, I don't care, I will sleep again if I have to. If there actually is a code interested in thread interrupted flag, I definitely don't want it to kick in, because I don't want to halt this operation, and in this case, swallowing without retry and without setting flag seems to be correct operation, however I did not see any mention, that swallow can be correct reaction in some situation.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Martin Mucha
  • 2,385
  • 1
  • 29
  • 49
  • What do you mean by "woken up in the middle"? You are woken by somebody calling `interrupt()`. The expected reaction to this is to stop what you are doing and kill your work cleanly. Why do you feel like somebody called `interrupt()` and didn't really mean it? – RealSkeptic Mar 15 '20 at 12:06
  • @RealSkeptic perhaps he was thinking about the elusive *spurious interrupts*. If it's legacy code and the operation is something that isn't easy to shutdown correctly while it's running, I would swallow it (and assume it's spurious). But I don't know anything about the codebase, so why should you listen to me? – Kayaman Mar 15 '20 at 12:12
  • 1
    You can check my [answer](https://stackoverflow.com/a/57576092/4956907) to similiar question here. Maybe it will be handy to you. – Michał Krzywański Mar 15 '20 at 12:59

1 Answers1

1

There is a good book on concurrency in Java: Java Concurrency in Practice. In chapter 7, section 7.1.3 there is this text:

Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

So, it is possible to swallow the interrupt in some situations.

Alex Sveshnikov
  • 4,214
  • 1
  • 10
  • 26