Java long running task Thread interrupt vs cancel flag

Tags: , , ,

I have a long running task, something like:

public void myCancellableTask() {
    while ( someCondition ) {

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?




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.

Source: stackoverflow