Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dant3/6d87f8eb61eb33c4afb932bd78ebc79f to your computer and use it in GitHub Desktop.
Save dant3/6d87f8eb61eb33c4afb932bd78ebc79f to your computer and use it in GitHub Desktop.
Interruptible-Cancellable-scala.concurrent.Future
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