Do I have to worry about InterruptedExceptions if I don’t interrupt anything myself?

Yes, you need to worry about InterruptedException, just as you need to worry for any other checked exception which you must either throw or handle.

Most of the times an InterruptedException signals a stop request, most likely due to the fact that the thread which was running your code was interrupted.

In your particular situation of a connection pool awaiting to aquire a connection, I would say that this is a cancellation issue and you need to abort the aquisition, cleanup, and restore the interrupted flag (see below).


As an example, if you’re using some sort of Runnable/Callable running inside an Executor then you need to handle the InterruptedException properly:

executor.execute(new Runnable() {

    public void run() {
         while (true) {
              try {
                 Thread.sleep(1000);
              } catch ( InterruptedException e) {
                  continue; //blah
              }
              pingRemoteServer();
         }
    }
});

This would mean that your task never obeys the interruption mechanism used by the executor and does not allow proper cancellation/shutdown.

Instead, the proper idiom is to restore the interrupted status and then stop execution:

executor.execute(new Runnable() {

    public void run() {
         while (true) {
              try {
                 Thread.sleep(1000);
              } catch ( InterruptedException e) {
                  Thread.currentThread().interrupt(); // restore interrupted status
                  break;
              }
              pingRemoteServer();
         }
    }
});

Useful resources:

  • Shutting down threads cleanly (Java Specialists)
  • Dealing with InterruptedException (Brian Goetz)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)