-1

I was task with implementing a background thread to do backend async processing with the twist being were certain cases where the job needed to be externally stopped.

I implemented it by wrapping everything within the Runnable in a try catch block and catch the InterruptionException, if caught the thread will simply return and exit.

Runnable task = () -> {
    try {
        while (true) {
            // do stuff 

            // sleep for interval
            Thread.sleep(this.checkInterval);
        }
    } catch (InterruptedException ex) {
            // cleanup and exit
            return; // exit thread
    } catch (Exception ex) {
            // cleanup and exit
            return; // exit thread
    }
};

I'm using the ExecutorService SingleThreadExecutor and submitting the job like the following.

this.job = executorService.submit(task);

Then I am stopping the thread using

boolean canceled = this.job.cancel(true);

It seems to work fine since the cancel causes an InterruptionException if the thread is running.

Is this code safe, meaning when cancel is called its always guaranteed to kill the thread?

greyfox
  • 6,426
  • 23
  • 68
  • 114
  • I'd be more worried about the process context being corrupted by terminating the thread while it's in the middle of something. – David Schwartz Apr 10 '17 at 18:42

1 Answers1

1

This approach might be OK, provided that your Runnable cooperates with it, and that the work that your Runnable performs can be safely interrupted at any time without causing problems such as inconsistent data.

Another common approach is to define a "running" flag within your Runnable, and set this to false when you want it to terminate. Your Runnable can then check this flag at a convenient and safe point in its processing (such as before each iteration of its main loop).

This approach might not terminate the task immediately, but it ensures that termination happens cleanly and without damage.

Any of these approaches require the cooperation of your Runnable - in general there is no way to safely and reliably terminate a Java thread without its cooperation.

DNA
  • 42,007
  • 12
  • 107
  • 146