Created
June 14, 2023 12:25
-
-
Save diesalbla/9bedd409121e6f116ea1f00212234a0a to your computer and use it in GitHub Desktop.
Scala SIP Coroutines - A simple example of blocking launcher.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Blocking extends Unwrapped[A], StarterLib: | |
val ec: ExecutionContextExecutorService = | |
ExecutionContext.fromExecutorService(Executors.newSingleThreadExecutor()) | |
sys.addShutdownHook(this.close) | |
def close: Unit = ec.close() | |
def apply(block: Continuation[A] ?=> A): A = | |
val boundary = new Boundary[A] { var result = null } | |
val latch = new CountDownLatch(1) | |
val baseContinuation = BuildContinuation( | |
ec, | |
res => { | |
boundary.result = res | |
latch.countDown() | |
}) | |
new Starter[A] { | |
override def invoke(completion: Continuation[A]): A | Any | Null = | |
given Continuation[A] = completion | |
block | |
}.start(baseContinuation) | |
latch.await() | |
boundary.result match | |
case Left(e) => throw e | |
case Right(Right(v)) => v.asInstanceOf[A] | |
case Right(v) => v.asInstanceOf[A] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment