Forked from viktorklang/InterruptibleCancellableFuture.scala
Last active
January 3, 2016 03:29
-
-
Save dwhjames/8402617 to your computer and use it in GitHub Desktop.
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._ | |
| import java.util.concurrent.atomic.AtomicReference | |
| def interruptableFuture[T](fun: Future[T] => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = { | |
| val p = Promise[T]() | |
| val f = p.future | |
| val aref = new AtomicReference[Thread](null) | |
| p tryCompleteWith Future { | |
| val thread = Thread.currentThread | |
| aref.set(thread) | |
| try fun(f) finally { | |
| val wasInterrupted = (aref getAndSet null) ne thread | |
| //Deal with interrupted flag of this thread in desired | |
| } | |
| } | |
| (f, () => { | |
| Option(aref getAndSet null) foreach { _.interrupt() } | |
| p.tryFailure(new CancellationException) | |
| }) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think I see a potential issue with my attempt at only using
AtomicReference.If the
getAndSetin thefinallyblock is reached first, thengetAndSetin the cancellation function will returnnulland the interrupt will not occur.However, if the
getAndSetin the cancelation function is reached first, thenwasInterruptedwill be bound totrue, but it is possible that some of the remainder of the finally block will execute before the interrupt is set. So, that code can’t meaningfully inspect or affect the interrupt status as there is no happens before relationship, but maybe that’s ok as the information is available inwasInterrupted.