Skip to content

Instantly share code, notes, and snippets.

@diesalbla
Created June 14, 2023 12:25
Show Gist options
  • Save diesalbla/9bedd409121e6f116ea1f00212234a0a to your computer and use it in GitHub Desktop.
Save diesalbla/9bedd409121e6f116ea1f00212234a0a to your computer and use it in GitHub Desktop.
Scala SIP Coroutines - A simple example of blocking launcher.
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