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 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) | |
}) | |
} |
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
getAndSet
in thefinally
block is reached first, thengetAndSet
in the cancellation function will returnnull
and the interrupt will not occur.However, if the
getAndSet
in the cancelation function is reached first, thenwasInterrupted
will 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
.