Dariusz Mydlarz

Dariusz Mydlarz

Software Craftsmanship, Project Management & Productivity

QR code

Geecon 2017: Don't Forget to Interrupt Your Thread.

I was at Geecon Kraków this year. On the last day, there was a talk given by Yegor Bugayenko (@yegor256) about handling InterruptedException. Did you know how to do it properly?

June 12, Krakow, Main Square
June 12, Krakow, Main Square

For most of the cases you (me as well!) do something like this:

void longComputaion() {
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

Yeah. Basically, for most of the cases, I swallow the exception, which is the worst thing that I could do.

So, what should we do instead? Take a look at below code snippet.

void longComputaion() {
    try {
        TimeUnit.SECONDS.sleep(10);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

We change swallowing interruption into calling Thread.currentThread().interrupt().

Why?

So we need to start with discussing the right way of stopping a thread. There is a Thread.stop() out there. But actually, it’s considered unsafe and marked as deprecated.

Instead of that you should use Thread.interrupt(). Calling that method makes yours thread internal interrupted flag set to true.

But very often you have a hierarchy of threads. The problem occurs when you call interrupt() and then just swallow the InterruptedException. That way your interruption doesn’t bubble up to threads higher in the hierarchy. And this is wrong.

There might be cases when swallowing is right, but for most of them, you should bubble the interruption up.

---

I found the talk very useful. If you wanna find out more on the topic please refer to original author’s blogpost: http://www.yegor256.com/2015/10/20/interrupted-exception.html