Skip to content

blocking and interruptible on Scala Native #4378

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

Open
wants to merge 4 commits into
base: series/3.x
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
* 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.std.Console
import cats.effect.tracing.Tracing

import java.time.{Instant, ZonedDateTime}

private[effect] abstract class IOCompanionMultithreadedPlatform { this: IO.type =>
private[this] val TypeDelay = Sync.Type.Delay
private[this] val TypeBlocking = Sync.Type.Blocking
private[this] val TypeInterruptibleOnce = Sync.Type.InterruptibleOnce
private[this] val TypeInterruptibleMany = Sync.Type.InterruptibleMany

/**
* Intended for thread blocking operations. `blocking` will shift the execution of the
* blocking operation to a separate threadpool to avoid blocking on the main execution
* context. See the thread-model documentation for more information on why this is necessary.
* Note that the created effect will be uncancelable; if you need cancelation then you should
* use [[interruptible[A](thunk:=>A):*]] or [[interruptibleMany]].
*
* {{{
* IO.blocking(scala.io.Source.fromFile("path").mkString)
* }}}
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync.blocking]].
*/
def blocking[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeBlocking, fn, Tracing.calculateTracingEvent(fn.getClass))
}

// this cannot be marked private[effect] because of static forwarders in Java
@deprecated("use interruptible / interruptibleMany instead", "3.3.0")
def interruptible[A](many: Boolean, thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(
if (many) TypeInterruptibleMany else TypeInterruptibleOnce,
fn,
Tracing.calculateTracingEvent(fn.getClass))
}

/**
* Like [[blocking]] but will attempt to abort the blocking operation using thread interrupts
* in the event of cancelation. The interrupt will be attempted only once.
*
* Note the following tradeoffs:
* - this has slightly more overhead than [[blocking]] due to the machinery necessary for
* the interrupt coordination,
* - thread interrupts are very often poorly considered by Java (and Scala!) library
* authors, and it is possible for interrupts to result in resource leaks or invalid
* states. It is important to be certain that this will not be the case before using this
* mechanism.
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync.interruptible[A](thunk:=>A):*]]
*/
def interruptible[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeInterruptibleOnce, fn, Tracing.calculateTracingEvent(fn.getClass))
}

/**
* Like [[blocking]] but will attempt to abort the blocking operation using thread interrupts
* in the event of cancelation. The interrupt will be attempted repeatedly until the blocking
* operation completes or exits.
*
* Note the following tradeoffs:
* - this has slightly more overhead than [[blocking]] due to the machinery necessary for
* the interrupt coordination,
* - thread interrupts are very often poorly considered by Java (and Scala!) library
* authors, and it is possible for interrupts to result in resource leaks or invalid
* states. It is important to be certain that this will not be the case before using this
* mechanism.
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync!.interruptibleMany]]
*/
def interruptibleMany[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeInterruptibleMany, fn, Tracing.calculateTracingEvent(fn.getClass))
}

def suspend[A](hint: Sync.Type)(thunk: => A): IO[A] =
if (hint eq TypeDelay)
apply(thunk)
else {
val fn = () => thunk
Blocking(hint, fn, Tracing.calculateTracingEvent(fn.getClass))
}

def realTimeInstant: IO[Instant] = asyncForIO.realTimeInstant

def realTimeZonedDateTime: IO[ZonedDateTime] = asyncForIO.realTimeZonedDateTime

/**
* Reads a line as a string from the standard input using the platform's default charset, as
* per `java.nio.charset.Charset.defaultCharset()`.
*
* The effect can raise a `java.io.EOFException` if no input has been consumed before the EOF
* is observed. This should never happen with the standard input, unless it has been replaced
* with a finite `java.io.InputStream` through `java.lang.System#setIn` or similar.
*
* @see
* `cats.effect.std.Console#readLineWithCharset` for reading using a custom
* `java.nio.charset.Charset`
*
* @return
* an IO effect that describes reading the user's input from the standard input as a string
*/
def readLine: IO[String] =
Console[IO].readLine
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package cats.effect

import cats.effect.unsafe.UnsafeNonFatal

import java.nio.channels.ClosedByInterruptException
import java.util.{concurrent => juc}
import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}

Expand Down Expand Up @@ -65,7 +64,7 @@ private[effect] abstract class IOFiberPlatform[A] extends AtomicBoolean(false) {
try {
Right(cur.thunk())
} catch {
case ex: ClosedByInterruptException => throw ex
case t if InterruptThrowable(t) => throw t
Comment on lines -68 to +67
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was the lack of InterruptedException here an oversight? Otherwise it seems like this is changing the semantic 🤔

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's incorporated in the matcher

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I think that was unclear: the previous matcher checked only for ClosedByInterruptException, but the new matcher now checks for both ClosedByInterruptException and InterruptedException. That's the change in semantic I'm referring to.


// this won't suppress InterruptedException:
case t if UnsafeNonFatal(t) => Left(t)
Expand All @@ -82,7 +81,7 @@ private[effect] abstract class IOFiberPlatform[A] extends AtomicBoolean(false) {

back
} catch {
case _: InterruptedException | _: ClosedByInterruptException =>
case t if InterruptThrowable(t) =>
null
} finally {
canInterrupt.tryAcquire()
Expand Down
122 changes: 2 additions & 120 deletions core/jvm/src/main/scala/cats/effect/IOCompanionPlatform.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,132 +16,14 @@

package cats.effect

import cats.effect.std.Console
import cats.effect.tracing.Tracing

import java.time.{Instant, ZonedDateTime}
import java.util.concurrent.{CompletableFuture, CompletionStage}

private[effect] abstract class IOCompanionPlatform { this: IO.type =>

private[this] val TypeDelay = Sync.Type.Delay
private[this] val TypeBlocking = Sync.Type.Blocking
private[this] val TypeInterruptibleOnce = Sync.Type.InterruptibleOnce
private[this] val TypeInterruptibleMany = Sync.Type.InterruptibleMany

/**
* Intended for thread blocking operations. `blocking` will shift the execution of the
* blocking operation to a separate threadpool to avoid blocking on the main execution
* context. See the thread-model documentation for more information on why this is necessary.
* Note that the created effect will be uncancelable; if you need cancelation then you should
* use [[interruptible[A](thunk:=>A):*]] or [[interruptibleMany]].
*
* {{{
* IO.blocking(scala.io.Source.fromFile("path").mkString)
* }}}
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync.blocking]].
*/
def blocking[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeBlocking, fn, Tracing.calculateTracingEvent(fn.getClass))
}

// this cannot be marked private[effect] because of static forwarders in Java
@deprecated("use interruptible / interruptibleMany instead", "3.3.0")
def interruptible[A](many: Boolean, thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(
if (many) TypeInterruptibleMany else TypeInterruptibleOnce,
fn,
Tracing.calculateTracingEvent(fn.getClass))
}

/**
* Like [[blocking]] but will attempt to abort the blocking operation using thread interrupts
* in the event of cancelation. The interrupt will be attempted only once.
*
* Note the following tradeoffs:
* - this has slightly more overhead than [[blocking]] due to the machinery necessary for
* the interrupt coordination,
* - thread interrupts are very often poorly considered by Java (and Scala!) library
* authors, and it is possible for interrupts to result in resource leaks or invalid
* states. It is important to be certain that this will not be the case before using this
* mechanism.
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync.interruptible[A](thunk:=>A):*]]
*/
def interruptible[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeInterruptibleOnce, fn, Tracing.calculateTracingEvent(fn.getClass))
}

/**
* Like [[blocking]] but will attempt to abort the blocking operation using thread interrupts
* in the event of cancelation. The interrupt will be attempted repeatedly until the blocking
* operation completes or exits.
*
* Note the following tradeoffs:
* - this has slightly more overhead than [[blocking]] due to the machinery necessary for
* the interrupt coordination,
* - thread interrupts are very often poorly considered by Java (and Scala!) library
* authors, and it is possible for interrupts to result in resource leaks or invalid
* states. It is important to be certain that this will not be the case before using this
* mechanism.
*
* @param thunk
* The side effect which is to be suspended in `IO` and evaluated on a blocking execution
* context
*
* Implements [[cats.effect.kernel.Sync!.interruptibleMany]]
*/
def interruptibleMany[A](thunk: => A): IO[A] = {
val fn = () => thunk
Blocking(TypeInterruptibleMany, fn, Tracing.calculateTracingEvent(fn.getClass))
}

def suspend[A](hint: Sync.Type)(thunk: => A): IO[A] =
if (hint eq TypeDelay)
apply(thunk)
else {
val fn = () => thunk
Blocking(hint, fn, Tracing.calculateTracingEvent(fn.getClass))
}
private[effect] abstract class IOCompanionPlatform extends IOCompanionMultithreadedPlatform {
this: IO.type =>

def fromCompletableFuture[A](fut: IO[CompletableFuture[A]]): IO[A] =
asyncForIO.fromCompletableFuture(fut)

def fromCompletionStage[A](completionStage: IO[CompletionStage[A]]): IO[A] =
asyncForIO.fromCompletionStage(completionStage)

def realTimeInstant: IO[Instant] = asyncForIO.realTimeInstant

def realTimeZonedDateTime: IO[ZonedDateTime] = asyncForIO.realTimeZonedDateTime

/**
* Reads a line as a string from the standard input using the platform's default charset, as
* per `java.nio.charset.Charset.defaultCharset()`.
*
* The effect can raise a `java.io.EOFException` if no input has been consumed before the EOF
* is observed. This should never happen with the standard input, unless it has been replaced
* with a finite `java.io.InputStream` through `java.lang.System#setIn` or similar.
*
* @see
* `cats.effect.std.Console#readLineWithCharset` for reading using a custom
* `java.nio.charset.Charset`
*
* @return
* an IO effect that describes reading the user's input from the standard input as a string
*/
def readLine: IO[String] =
Console[IO].readLine

}
27 changes: 27 additions & 0 deletions core/jvm/src/main/scala/cats/effect/InterruptThrowable.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* 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 java.nio.channels.ClosedByInterruptException

private[effect] object InterruptThrowable {
def apply(t: Throwable): Boolean = t match {
case _: InterruptedException => true
case _: ClosedByInterruptException => true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ClosedByInterruptException also landed in SN 0.5.7.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Le sigh… Well, we'll remove my shims when we do.

case _ => false
}
}
49 changes: 2 additions & 47 deletions core/native/src/main/scala/cats/effect/IOCompanionPlatform.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,51 +16,6 @@

package cats.effect

import cats.effect.std.Console

import java.time.Instant

private[effect] abstract class IOCompanionPlatform { this: IO.type =>

private[this] val TypeDelay = Sync.Type.Delay

def blocking[A](thunk: => A): IO[A] =
// do our best to mitigate blocking
IO.cede *> apply(thunk).guarantee(IO.cede)

private[effect] def interruptible[A](many: Boolean, thunk: => A): IO[A] = {
val _ = many
blocking(thunk)
}

def interruptible[A](thunk: => A): IO[A] = interruptible(false, thunk)

def interruptibleMany[A](thunk: => A): IO[A] = interruptible(true, thunk)

def suspend[A](hint: Sync.Type)(thunk: => A): IO[A] =
if (hint eq TypeDelay)
apply(thunk)
else
blocking(thunk)

def realTimeInstant: IO[Instant] = asyncForIO.realTimeInstant

/**
* Reads a line as a string from the standard input using the platform's default charset, as
* per `java.nio.charset.Charset.defaultCharset()`.
*
* The effect can raise a `java.io.EOFException` if no input has been consumed before the EOF
* is observed. This should never happen with the standard input, unless it has been replaced
* with a finite `java.io.InputStream` through `java.lang.System#setIn` or similar.
*
* @see
* `cats.effect.std.Console#readLineWithCharset` for reading using a custom
* `java.nio.charset.Charset`
*
* @return
* an IO effect that describes reading the user's input from the standard input as a string
*/
def readLine: IO[String] =
Console[IO].readLine

private[effect] abstract class IOCompanionPlatform extends IOCompanionMultithreadedPlatform {
this: IO.type =>
}
Loading
Loading