Created
September 30, 2016 14:18
-
-
Save benhardy/a9b50394e5a073001893d9ea3572b762 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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