Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

java - Do I have to worry about InterruptedExceptions if I don't interrupt anything myself?

I'm using java.util.concurrent.Semaphore in a hobby project. It's used in a connection pool class I'm writing. I can use it with little fuss, except for this method:

public void acquire(int permits) throws InterruptedException

which forces me to handle the InterruptedException. Now, I'm not sure what "interrupting" a Thread even means and I'm never doing it (well, not explicitly anyway) in my code. Does this mean I can ignore the exception? How should I handle it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...