Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dwhjames/8485117 to your computer and use it in GitHub Desktop.
Save dwhjames/8485117 to your computer and use it in GitHub Desktop.
import scala.concurrent._
def interruptableFuture[T](fun: Future[T] => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = {
val p = Promise[T]()
val f = p.future
val lock = new Object
var currentThread: Thread = null
def updateCurrentThread(newThread: Thread): Thread = {
val old = currentThread
currentThread = newThread
old
}
p tryCompleteWith Future {
val thread = Thread.currentThread
lock.synchronized { updateCurrentThread(thread) }
try fun(f) finally {
val wasInterrupted = lock.synchronized { updateCurrentThread(null) } ne thread
//Deal with interrupted flag of this thread in desired
}
}
(f, () => {
lock.synchronized { Option(updateCurrentThread(null)) foreach { _.interrupt() } }
p.tryFailure(new CancellationException)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment