Skip to content

Clean up and DRY IOApp implementations #4361

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

Draft
wants to merge 5 commits into
base: series/3.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
35 changes: 3 additions & 32 deletions core/js/src/main/scala/cats/effect/IOApp.scala
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ import scala.util.Try
* @see
* [[IOApp.Simple]]
*/
trait IOApp {

private[this] var _runtime: unsafe.IORuntime = null
trait IOApp extends IOAppPlatform {

/**
* The runtime which will be used by `IOApp` to evaluate the [[IO]] produced by the `run`
Expand All @@ -160,7 +158,7 @@ trait IOApp {
*
* This value is guaranteed to be equal to [[unsafe.IORuntime.global]].
*/
protected def runtime: unsafe.IORuntime = _runtime
protected def runtime: unsafe.IORuntime = installedRuntime

/**
* The configuration used to initialize the [[runtime]] which will evaluate the [[IO]]
Expand Down Expand Up @@ -202,34 +200,7 @@ trait IOApp {
def run(args: List[String]): IO[ExitCode]

final def main(args: Array[String]): Unit = {
val installed = if (runtime == null) {
import unsafe.IORuntime

val installed = IORuntime installGlobal {
val compute = IORuntime.createBatchingMacrotaskExecutor(reportFailure = t =>
reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime))

IORuntime(
compute,
compute,
IORuntime.defaultScheduler,
() => IORuntime.resetGlobal(),
runtimeConfig)
}

_runtime = IORuntime.global

installed
} else {
unsafe.IORuntime.installGlobal(runtime)
}

if (!installed) {
System
.err
.println(
"WARNING: Cats Effect global runtime already initialized; custom configurations will be ignored")
}
setupGlobalRuntime()

if (LinkingInfo.developmentMode && isStackTracing) {
val listener: js.Function0[Unit] = () =>
Expand Down
35 changes: 35 additions & 0 deletions core/js/src/main/scala/cats/effect/IOAppPlatform.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright 2020-2025 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats.effect

import cats.effect.unsafe.IORuntime

trait IOAppPlatform extends IOAppCommon {
this: IOApp =>

private[effect] def defaultGlobalRuntime: IORuntime = {
val compute = IORuntime.createBatchingMacrotaskExecutor(reportFailure = t =>
reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime))

IORuntime(
compute,
compute,
IORuntime.defaultScheduler,
() => IORuntime.resetGlobal(),
runtimeConfig)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2020-2025 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats.effect

import scala.concurrent.ExecutionContext

import java.util.concurrent.ArrayBlockingQueue

trait IOAppMultiThreaded {
// arbitrary constant is arbitrary
private[effect] lazy val queue = new ArrayBlockingQueue[AnyRef](32)

private[effect] def handleTerminalFailure(t: Throwable): Unit = {
queue.clear()
queue.put(t)
}

private[effect] def defaultMainThread: ExecutionContext
}
85 changes: 5 additions & 80 deletions core/jvm/src/main/scala/cats/effect/IOApp.scala
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import cats.syntax.all._
import scala.concurrent.{blocking, CancellationException, ExecutionContext}
import scala.concurrent.duration._

import java.util.concurrent.{ArrayBlockingQueue, CountDownLatch}
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicInteger

/**
Expand Down Expand Up @@ -140,9 +140,7 @@ import java.util.concurrent.atomic.AtomicInteger
* @see
* [[IOApp.Simple]]
*/
trait IOApp {

private[this] var _runtime: unsafe.IORuntime = null
trait IOApp extends IOAppPlatform {

/**
* The runtime which will be used by `IOApp` to evaluate the [[IO]] produced by the `run`
Expand All @@ -157,7 +155,7 @@ trait IOApp {
*
* This value is guaranteed to be equal to [[unsafe.IORuntime.global]].
*/
protected def runtime: unsafe.IORuntime = _runtime
protected def runtime: unsafe.IORuntime = installedRuntime

/**
* The configuration used to initialize the [[runtime]] which will evaluate the [[IO]]
Expand Down Expand Up @@ -198,14 +196,6 @@ trait IOApp {
protected def computeWorkerThreadCount: Int =
Math.max(2, Runtime.getRuntime().availableProcessors())

// arbitrary constant is arbitrary
private[this] lazy val queue = new ArrayBlockingQueue[AnyRef](32)

private[this] def handleTerminalFailure(t: Throwable): Unit = {
queue.clear()
queue.put(t)
}

/**
* Executes the provided actions on the JVM's `main` thread. Note that this is, by definition,
* a single-threaded executor, and should not be used for anything which requires a meaningful
Expand All @@ -221,27 +211,7 @@ trait IOApp {
* calling thread (for example, LWJGL). In these scenarios, it is recommended that the
* absolute minimum possible amount of work is handed off to the main thread.
*/
protected def MainThread: ExecutionContext =
if (queue eq queue)
new ExecutionContext {
def reportFailure(t: Throwable): Unit =
t match {
case t if UnsafeNonFatal(t) =>
IOApp.this.reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime)

case t =>
handleTerminalFailure(t)
}

def execute(r: Runnable): Unit =
if (!queue.offer(r)) {
runtime.blocking.execute(() => queue.put(r))
}
}
else
throw new UnsupportedOperationException(
"Your IOApp's super class has not been recompiled against Cats Effect 3.4.0+."
)
protected def MainThread: ExecutionContext = defaultMainThread

/**
* Configures the action to perform when unhandled errors are caught by the runtime. An
Expand Down Expand Up @@ -395,52 +365,7 @@ trait IOApp {
val isForked = Thread.currentThread().getId() == 1
if (!isForked) onNonMainThreadDetected()

val installed = if (runtime == null) {
import unsafe.IORuntime

val installed = IORuntime installGlobal {
val (compute, poller, compDown) =
IORuntime.createWorkStealingComputeThreadPool(
threads = computeWorkerThreadCount,
reportFailure = t => reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime),
blockedThreadDetectionEnabled = blockedThreadDetectionEnabled,
pollingSystem = pollingSystem,
uncaughtExceptionHandler = (_, t) => handleTerminalFailure(t)
)

val (blocking, blockDown) =
IORuntime.createDefaultBlockingExecutionContext(
threadPrefix = "io-blocking",
reportFailure =
(t: Throwable) => reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime)
)

IORuntime(
compute,
blocking,
compute,
List(poller),
{ () =>
compDown()
blockDown()
IORuntime.resetGlobal()
},
runtimeConfig)
}

_runtime = IORuntime.global

installed
} else {
unsafe.IORuntime.installGlobal(runtime)
}

if (!installed) {
System
.err
.println(
"WARNING: Cats Effect global runtime already initialized; custom configurations will be ignored")
}
setupGlobalRuntime()

if (isStackTracing) {
val liveFiberSnapshotSignal = sys
Expand Down
78 changes: 78 additions & 0 deletions core/jvm/src/main/scala/cats/effect/IOAppPlatform.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright 2020-2025 Typelevel
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package cats.effect

import cats.effect.unsafe.{IORuntime, UnsafeNonFatal}

import scala.concurrent.ExecutionContext

trait IOAppPlatform extends IOAppCommon with IOAppMultiThreaded {
this: IOApp =>

private[effect] def defaultMainThread: ExecutionContext = {
if (queue eq queue)
new ExecutionContext {
def reportFailure(t: Throwable): Unit =
t match {
case t if UnsafeNonFatal(t) =>
IOAppPlatform.this.reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime)

case t =>
handleTerminalFailure(t)
}

def execute(r: Runnable): Unit =
if (!queue.offer(r)) {
runtime.blocking.execute(() => queue.put(r))
}
}
else
throw new UnsupportedOperationException(
"Your IOApp's super class has not been recompiled against Cats Effect 3.4.0+."
)
}

private[effect] def defaultGlobalRuntime: IORuntime = {
val (compute, poller, compDown) =
IORuntime.createWorkStealingComputeThreadPool(
threads = computeWorkerThreadCount,
reportFailure = t => reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime),
blockedThreadDetectionEnabled = blockedThreadDetectionEnabled,
pollingSystem = pollingSystem,
uncaughtExceptionHandler = (_, t) => handleTerminalFailure(t)
)

val (blocking, blockDown) =
IORuntime.createDefaultBlockingExecutionContext(
threadPrefix = "io-blocking",
reportFailure =
(t: Throwable) => reportFailure(t).unsafeRunAndForgetWithoutCallback()(runtime)
)

IORuntime(
compute,
blocking,
compute,
List(poller),
{ () =>
compDown()
blockDown()
IORuntime.resetGlobal()
},
runtimeConfig)
}
}
Loading
Loading