Forked from viktorklang/InterruptibleCancellableFuture.scala
Created
January 18, 2014 01:56
-
-
Save dwhjames/8485117 to your computer and use it in GitHub Desktop.
This file contains 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
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