Skip to content

Instantly share code, notes, and snippets.

@jedws
Created August 17, 2011 07:40
Show Gist options
  • Save jedws/1151046 to your computer and use it in GitHub Desktop.
Save jedws/1151046 to your computer and use it in GitHub Desktop.
alternate Threaded
trait Threaded[T] extends Runnable {
@volatile private var stopping = false
@volatile private var thread: Thread = _
def afterPropertiesSet() {
thread = new Thread(this)
thread.start()
}
def destroy() {
stopping = true
thread.interrupt()
}
def run {
val t = before()
Repeat.until(stopping) { task(t) } {
handling(classOf[InterruptedException]) by { t => stopping = true }
}
after(t)
}
def task(t: T): Unit
def before(): T
def after(t: T): Unit
}
object Repeat {
def until(finished: => Boolean)(task: => Unit)(handlers: Catch[Unit]) = {
@annotation.tailrec
def loop {
if (!finished) {
handlers apply task
loop
}
}
loop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment