0

I was thinking that I could calmly Thread.sleep() on an interrupted thread. Sonar doesn't think so, of course.

In some circumstates we should waiting for conditions, even if an interrupt occured. Is there anything wrong, for example, with the code below? Is there any better solution?

private void waitFinish() {
    boolean wasInterrupted = false;
    while (asyncProgressCounter.get() > 0) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) { // NOSONAR
            wasInterrupted = true;
        }
    }
    if (wasInterrupted) {
        Thread.currentThread().interrupt();
    }
    onFinish();
}
  • You don't deal with interrupts in Java running in some JVM. Perhaps with signals and these are operating system-specific. Signals are mostly Unix-like, and thread-unfriendly. Read Operating systems: three easy pieces – Basile Starynkevitch Jun 23 at 15:55
  • You should think in terms of threads running event loops so think in terms of message passing – Basile Starynkevitch Jun 23 at 15:58
  • You ask if there is a better solution. What do you want to achieve? It looks like you are delaying shutdown of this thread (possibly forever) and trying to do onFinish() before shutting down. Is that your intent? Is your code interrupting this thread? Or are you anticipating that a library or container will interrupt it? – joshp Jun 23 at 17:33
  • My intent is waiting for all tasks to finish, than run some shutdown code. (These tasks are callbacks invoked by a third party library.) Technically, users of my API could set the 'interrupted' flag. (But, even if no interrupt could be thrown, I must catch this exception, and Sonar will alert me, if I ignore it.) – Dávid Horváth Jun 23 at 19:19
  • 1
    @BasileStarynkevitch the Java thread interrupt mechanism is not the low level interrupt mechanism you're thinking of. – Kayaman Jun 24 at 9:50
0

The displayed code is correct if you need to keep the state of the interrupt status of the thread. As Thread.sleep() clears the status, you need the additional wasInterrupted flag.

In most code you don't see the "full version" like this, because it's often not useful information. I don't really see a reason for it here either. Is there other code that examines the interrupted status of that thread? If not, you don't need the flag and you can just use an empty catch block.

(I'm assuming you have to resort to "busy-sleep" because the async operations have no other way of notifying they're finished (such as a CountDownLatch). While the code represents the correct way to handle keeping the interrupt status, it's not a good general purpose approach.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.