How to shutdown Cats Effect Runtime

241 Views Asked by At

Is there a way to shutdown the cats effect runtime from within an application, similar to System.exit(0)?

There is a shutdown method on IORuntime but it is not documented and it behaves weirdly when I call it on IORuntime.global: it does not shut the application down, it just seems to hang it. Also accessing runtime on my IOApp just throws a NullPointerException so I cannot use that. What I want to do is: from within my application a want to make the complete runtime shutdown cleanly, i.e. cancelling the main fiber and running all finalisers. I know I can implement such a shutdown-hook myself, but I was wondering if that is already supported somehow by cats effect, which is what the existence of these methods suggest.

1

There are 1 best solutions below

0
Daenyth On

You can do something like (pseudocode)

object MyApp extends IOApp.Simple {
  def run =
    Deferred[IO].flatMap { shutdown =>
      val app = buildMyAppResource(shutdown)
      IO.race(shutdown.get, app.useForever)
    }
}

Inside your app code, it can call shutdown.complete(()). The IO.race will run both fibers until one completes, then cancel the other. The useForever means your app won't close on its own, and the shutdown.get will wait until it's completed. So when your app calls shutdown.complete, the app resource will be interrupted and cancelled, letting the program exit after doing a clean resource release