package STM
import scala.concurrent.stm.Ref
import scala.concurrent.stm.atomic
import scala.concurrent.stm.retry
import scala.concurrent.stm.retryFor
import java.util.Timer
import java.util.TimerTask
import java.util.concurrent.TimeUnit
object SensibleWait {
val start = System.nanoTime()
val cups = Ref(24)
def fillCup(numberOfCups: Int) = {
atomic {
implicit tx =>
{
if (cups() < numberOfCups) {
println("retry........ at " + (System.nanoTime() - start) / 1.0e9)
retryFor(5, TimeUnit.SECONDS)
}
cups.swap(cups() - numberOfCups)
println("Fill up ... " + numberOfCups)
println("........ at " + (System.nanoTime() - start)/1.0e9)
}
}
}
def main(args : Array[String]) = {
val timer = new Timer(true)
timer.schedule(new TimerTask() {
def run() {
println("Refilling.... at " + (System.nanoTime() - start)/1.0e9)
atomic {
implicit tx => cups() = 24
}
}
}, 5000)
SensibleWait.fillCup(20)
SensibleWait.fillCup(10)
try {
SensibleWait.fillCup(22)
} catch {
case ex : Throwable => println("Failed: " + ex.getMessage())
}
println("Ending.....")
}
}
阅读(834) | 评论(0) | 转发(0) |