Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def spendNotMoreThan[T](time: Duration) = new {
def on(op: => Result[T]): Result[T] = {
var res:Result[T] = Empty
var done = new AtomicBoolean(false)
val nanos = time.toNanos
val upto = System.nanoTime + nanos
val worker = new Thread {
override def run {
res = op
done.set(true)
}
}
worker.setPriority(1)
worker.start
val sentinel = new Thread {
override def run {
while (!done.get && upto > System.nanoTime) try {
Thread.sleep((upto - System.nanoTime + 999999) / 1000000) // java sleep does not use nanos
}
worker.stop
}
}
sentinel.setPriority(5)
sentinel.start
sentinel.join
if (done.get) res else Result.error(s"Timeout after $time")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment