Forked from viktorklang/InterruptibleCancellableFuture.scala
Created
July 15, 2016 09:48
-
-
Save dant3/6d87f8eb61eb33c4afb932bd78ebc79f to your computer and use it in GitHub Desktop.
Interruptible-Cancellable-scala.concurrent.Future
This file contains hidden or 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 { | |
if (f.isCompleted) throw new CancellationException | |
else { | |
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)) exists { | |
t => | |
t.interrupt() | |
p.tryFailure(new CancellationException) | |
} | |
} | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment