3

What is the proper behavior to avoid resource/memory leak? Is it required/correct to cancel failed Fiber?

val someEffect: F[Unit] = //...

def someFiber[F[_]: MonadError[?[_], Throwable]](fa: F[Fiber[F, Unit]]): F[Unit] =
  for {
      fiber <- fa
      _     <- fiber.join handleErrorWith { _ =>
            //Is this cancel required?
            fiber.cancel *> someEffect
      }
  } yield ()

My concern is about cancel when handling Fiber.join error? Is it required?

Some Name
  • 8,555
  • 5
  • 27
  • 77
  • 3
    I am pretty sure it isn't necessary. A failed fiber already finished, thus the cancel is already redundant. Maybe, the real code canceled another fiber? – Luis Miguel Mejía Suárez May 22 '20 at 14:18
  • @LuisMiguelMejíaSuárez I can imagine the following use case: We have a fiber represneting a computation on a cluster. In case some unrecoverable error occurrs (like all replicas lost) we'd like to deallocate all the cluster and start the computation from scratch. What do you think? – Some Name May 22 '20 at 14:23
  • 1
    The cluster would be a resource, when you finish using it, it will be closed / deallocated. – Luis Miguel Mejía Suárez May 22 '20 at 14:28
  • 2
    If one operation fails you might consider canceling some other computation that would run in parallel and wouldn't know that it's results are no longer necessary (it could combine its results with failed IO somewhere later in pipeline), but here when you call cancel the fiber already failed. If you look at docs example https://typelevel.org/cats-effect/datatypes/fiber.html `cancel` is called in `handleErrorWith` of some other computation, not in the fiber run. – Mateusz Kubuszok May 22 '20 at 14:38

0 Answers0