Marc
Marc

Reputation: 16522

Best way to cancel task with functions that don't implement InterruptedException

I would like to cancel the following task

fooFuture = executor.submit(() ->  {
    bar1();
    bar2();
    bar3();
});

The bar functions don't implement InterruptedException.

Is there a way I can catch an interrupt without checking Thread.currentThread().isInterruped(); after every instruction?

Upvotes: 0

Views: 32

Answers (2)

gati sahu
gati sahu

Reputation: 2641

I believe that there's no way in Java to just kill off a thread if during execution not implemented InterruptedException . If the thread is executing, it just sets a flag and it's up to the thread to notice it. if the thread is waiting or sleeping, it will throw an InterruptedException.

kill the process in which the thread is running. (E.g., call System.exit(int).)

Upvotes: 1

VGR
VGR

Reputation: 44414

In a word, no. You don’t have to check after every line, of course, but methods which can take a long time to execute are responsible for properly handling interrupts. If they don’t, you’re out of luck, unfortunately.

Upvotes: 1

Related Questions