0

How can I write idiomatic code that is potentially used in a Thread and thus needs/should support interruption?

Thread.close() is deprecated. My understanding is, that any code that might be relied on from within a thread consequently needs to support/check the interrupt() flag of the Thread object to allow the thread creator to stop a thread proper at a time of their choosing. However, it seems rather silly and non idiomatic to write code such as:

def interruptibleFunction() {
   doSmth()
   if (Thread.interrupted())
      throw new InterruptedException();
   doSmth()
   if (Thread.interrupted())
      throw new InterruptedException();
   doSmth()
   if (Thread.interrupted())
      throw new InterruptedException();
   //... and so on and so forth
}

I want my code to terminate as soon as (or as timely as possible as) the corresponding thread has been interrupted/is supposed to stop. Each of the doSmth() might take a long time, which could be the actual reason for the interrupt in the first place. Consequently, it would be rather rude by the function to proceed even if an interrupt has been called.

Is this the only way to write interruptible code or is there another more idiomatic way?

Sim
  • 4,199
  • 4
  • 39
  • 77
  • 2
    Using `Thread` is already no idiomatic so why care at all. – Luis Miguel Mejía Suárez Dec 09 '22 at 21:00
  • @LuisMiguelMejíaSuárez what would you suppose is a better solution? `Future` does not support interrupt as far as I know and even if it would I would have the same issue wouldn't I? – Sim Dec 09 '22 at 21:04
  • 3
    **cats-effect** or **ZIO** both support cancellation out of the box. – Luis Miguel Mejía Suárez Dec 09 '22 at 21:39
  • 1. Create a separate (maybe single threaded) `ExecutionContext` for the `Future` that should be "interruptable", 2. perform a chain of operations with `map` and `flatMap` using this EC, treating each `map`/`flatMap` as a place for possible interruption, 3. to interrupt shutdown the thread pool. Not as performant as cancellable IO, but can be build from existing components without designing your own monad. – Mateusz Kubuszok Dec 10 '22 at 14:42
  • And besides Cats Effect IO and ZIO there were also Twitter's Futures - it's a bit of a question mark what is going to happen with Twitters OSS now ,but Twitter's Futures predate Scala's Futures and they have different abilities - including interruptability. If you don't want to go into pure FP I would monitor the status of TT Futures as they do exactly what you ask for. – Mateusz Kubuszok Dec 10 '22 at 14:51

0 Answers0