Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dwhjames/8402617 to your computer and use it in GitHub Desktop.
Save dwhjames/8402617 to your computer and use it in GitHub Desktop.
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)
})
}
@dwhjames
Copy link
Author

I think I see a potential issue with my attempt at only using AtomicReference.

If the getAndSet in the finally block is reached first, then getAndSet in the cancellation function will return null and the interrupt will not occur.

However, if the getAndSet in the cancelation function is reached first, then wasInterrupted will be bound to true, 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 in wasInterrupted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment