Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize Dispatcher#{unsafeRunAsync,unsafeRunAndForget} #3822

Merged
merged 3 commits into from
Sep 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions std/shared/src/main/scala/cats/effect/std/Dispatcher.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package cats.effect.std

import cats.effect.kernel.{Async, Outcome, Resource}
import cats.effect.std.Dispatcher.parasiticEC
import cats.syntax.all._

import scala.annotation.tailrec
Expand Down Expand Up @@ -68,28 +69,26 @@ trait Dispatcher[F[_]] extends DispatcherPlatform[F] {
/**
* Submits an effect to be executed with fire-and-forget semantics.
*/
def unsafeRunAndForget[A](fa: F[A]): Unit = {
unsafeRunAsync(fa) {
case Left(t) => t.printStackTrace()
case Right(_) => ()
}
}
def unsafeRunAndForget[A](fa: F[A]): Unit =
unsafeToFuture(fa).onComplete {
case Failure(ex) => ex.printStackTrace()
case _ => ()
}(parasiticEC)

// package-private because it's just an internal utility which supports specific implementations
// anyone who needs this type of thing should use unsafeToFuture and then onComplete
private[std] def unsafeRunAsync[A](fa: F[A])(cb: Either[Throwable, A] => Unit): Unit = {
// this is safe because the only invocation will be cb
implicit val parasitic: ExecutionContext = new ExecutionContext {
def execute(runnable: Runnable) = runnable.run()
def reportFailure(t: Throwable) = t.printStackTrace()
}

unsafeToFuture(fa).onComplete(t => cb(t.toEither))
}
private[std] def unsafeRunAsync[A](fa: F[A])(cb: Either[Throwable, A] => Unit): Unit =
unsafeToFuture(fa).onComplete(t => cb(t.toEither))(parasiticEC)
}

object Dispatcher {

private val parasiticEC: ExecutionContext = new ExecutionContext {
def execute(runnable: Runnable) = runnable.run()

def reportFailure(t: Throwable) = t.printStackTrace()
}

private[this] val Cpus: Int = Runtime.getRuntime().availableProcessors()

private[this] val Noop: () => Unit = () => ()
Expand Down