Skip to content

Instantly share code, notes, and snippets.

@benhardy
Created September 30, 2016 14:18
Show Gist options
  • Save benhardy/a9b50394e5a073001893d9ea3572b762 to your computer and use it in GitHub Desktop.
Save benhardy/a9b50394e5a073001893d9ea3572b762 to your computer and use it in GitHub Desktop.
/**
* simple demo of using Phasers to sync completion and waiting for things to complete.
*/
import java.util.concurrent._
import java.lang.{Thread, Runnable}
/**
* Run a function in another thread, yeah it's ugly, whatever, this is a demo.
* This is not the interesting part.
*/
def runBackground(f: ()=>Unit) = {
new Thread(
new Runnable {
override def run: Unit = {
f.apply()
}
}
).start
}
/**
* wait for someone to arrive with this Phaser
*/
def patient(phaser:Phaser, millis:Long) {
println("patient waiting")
try {
phaser.awaitAdvanceInterruptibly(0, millis, TimeUnit.MILLISECONDS)
println("patient done waiting")
} catch {
case te: TimeoutException => {
println("too slow! i gave up");
}
}
}
/**
* do something slow then arrive at the given Phaser
*/
def slowWriter(phaser:Phaser, slowness:Long): Unit = {
phaser.register()
try {
println("slow writer snoozing")
Thread.sleep(slowness) // do some slow thing, yeah we know this is ugly.
println("slow writer arriving")
} finally {
phaser.arrive()
println("slow writer done")
}
}
def demo(slowness:Long, patience:Long) {
val phaser = new Phaser
runBackground(() => slowWriter(phaser, slowness))
patient(phaser, patience)
}
demo(1000, 5000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment