Skip to content
Advertisement

Java long running task Thread interrupt vs cancel flag

I have a long running task, something like:

public void myCancellableTask() {
    while ( someCondition ) {
       checkIfCancelRequested();
       doSomeWork();
    }
 }

The task can be cancelled (a cancel is requested and checkIfCancelRequested() checks the cancel flag). Generally when I write cancellable loops like this, I use a flag to indicate that a cancel has been requested. But, I know I could also use Thread.interrupt and check if the thread has been interrupted. I’m not sure which would be the preferred approach and why, thoughts?

thanks,

Jeff

Advertisement

Answer

Interrupt will blast the thread out of a list of specified wait conditions. Your own cancel flag will not. If you want to interrupt waits on IO and events, use interrupt. Otherwise use your own.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement