Skip to content

Instantly share code, notes, and snippets.

@lbialy
Created March 2, 2024 22:10
Show Gist options
  • Save lbialy/d2cb9e5f1c3fbe5c553482c53332c204 to your computer and use it in GitHub Desktop.
Save lbialy/d2cb9e5f1c3fbe5c553482c53332c204 to your computer and use it in GitHub Desktop.
Demonstration of backpressure with Loom
//> using scala 3.3.3
//> using jvm graalvm-java21:21.0.2
//> using dep com.softwaremill.ox::core:0.0.21
import ox.*
import java.util.concurrent.*
@main def main = supervised {
val queue = ArrayBlockingQueue[Int](5)
val queueProducer = fork {
1 to 100 foreach { i =>
queue.put(i)
println(s"produced $i")
}
}
val queueConsumer = fork {
var consumed = 0
while consumed < 100 do
val i = queue.take()
consumed += 1
println(s"consumed $i")
if consumed % 10 == 0 then
println("consumed another ten elements, sleeping")
Thread.sleep(1000)
}
queueProducer.join()
queueConsumer.join()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment