3

In very ancient days, there used to be a way to "stop" or "kill" a thread, though this is has been deprecated due to it allowing system instability. I noticed though, it's possible to "cancel" a running future. The quotes are there because I don't know how the thread is treated at an OS level.

For my education, What's the difference between canceling a Future, effectively canceling the thread, and stopping the thread? Why is cancelling okay, but stopping/killing a thread in the old days bad?

3
  • 1
    From some digging, cancelling futures (in most implementations) sets a state field to CANCELLED, and if it does interrupt any running thread, calls Thread#interrupt. The #interrupt method will not push a Throwable (exception) onto the stack of the targetted thread, but instead set a flag for the thread that can be checked via Thread#isInterrupted. However, Thread#stop will cause the thread to forcibly end via an arbitrary (and likely unhandled) exception.
    – Rogue
    Mar 11, 2022 at 22:34
  • Threads can be states of RUNNABLE, RUNNING, WAITING and NEW. Is CANCELLED another one of those states or is it a separate state?
    – Woodsman
    Mar 12, 2022 at 3:26
  • It was an implementation-specific flag in classes like FutureTask that implement from Future. This is distinct from the concept of Thread states.
    – Rogue
    Mar 12, 2022 at 3:35

1 Answer 1

5

Cancelling tells the Future its result is no longer desired (if it hasn't already completed), and lets it stop cleanly, whereas Thread.stop() kills the underlying native thread and releases all its monitors. The thread doesn't get a chance to wrap up what it was doing or put anything into a known, good state.

The difference is, one sends a message, but lets the recipient respond to the message on its own terms, and the other just forcefully stops it, effectively instantly. (Letting the recipient respond in its own way can even mean that the job will continue to execute, since different implementations of Future may handle cancellation differently, but any result will still be ignored.)

It's like the difference between putting out the red flag in an auto race, telling a car it needs to come in to the pit stop on the next lap, versus suddenly putting a wall in the middle of the racetrack right in front of the car, which it then crashes into.

1
  • 1
    Nice answer. I just can add that lets the recipient respond to the message on its own terms eventually can mean that the job will continue to execute(and the thread can even hang on it). The result of it will be ignored anyway.
    – msangel
    Mar 11, 2022 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.