Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Interruptible-Cancellable-scala.concurrent.Future
/*
Copyright 2018 Viktor Klang
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import scala.concurrent._
import java.util.concurrent.CancellationException
final class Interrupt extends (() => Boolean) {
private[this] final var state: AnyRef = null
override final def apply(): Boolean = this.synchronized {
state match {
case null =>
state = this
true
case _: this.type => false
case t: Thread =>
state = this
t.interrupt()
true
}
}
private[this] final def enter(): Boolean =
this.synchronized {
state match {
case _: this.type => false
case null =>
state = Thread.currentThread
true
}
}
private[this] final def exit(): Boolean =
this.synchronized {
state match {
case _: this.type => false
case t: Thread =>
state = this
true
}
}
def interruptibly[T](body: =>T): T =
if (enter()) {
try body catch {
case ie: InterruptedException => throw new CancellationException()
} finally {
if(!exit() && Thread.interrupted())
() // If we were interrupted and flag was not cleared
}
} else throw new CancellationException()
}
def interruptibly[T](body: => T)(implicit ec: ExecutionContext): (Future[T], () => Boolean) = {
val interrupt = new Interrupt()
(Future(interrupt.interruptibly(body))(ec), interrupt)
}
@dwhjames

This comment has been minimized.

Copy link

@dwhjames dwhjames commented Dec 5, 2013

Stumbled across this recently… maybe I’m missing something, so hopefully you can help me out, but it seems strange to me to wrap the atomic set and getAndSetmethods on aref in a block that is synchronized on aref.

@viktorklang

This comment has been minimized.

Copy link
Owner Author

@viktorklang viktorklang commented Dec 13, 2013

@dwhjames You're absolutely right, the reason for using AtomicReference was to get:
A) getAndSet — so I didn't need to implement that myself
B) unify the instance that holds the current Thread with the instance used as the monitor for the lock

See the updated version and compare it to the old :)

@dwhjames

This comment has been minimized.

Copy link

@dwhjames dwhjames commented Dec 17, 2013

Huh, I was anticipating going the other way… implementing this entirely with AtomicReference. Am I missing something… does that not give you the desired semantics?

@viktorklang

This comment has been minimized.

Copy link
Owner Author

@viktorklang viktorklang commented Jan 10, 2014

Gist it?

@dwhjames

This comment has been minimized.

Copy link

@dwhjames dwhjames commented Jan 17, 2014

Sorry, I’ve realized that I’ve split the conversation, as I added a comment on my gist with an analysis of the interleavings.

@dwhjames

This comment has been minimized.

Copy link

@dwhjames dwhjames commented Jan 17, 2014

Maybe there is another issue here…

It is possible for wasInterrupted == false, but the promise to still be completed with the cancellation exception. In which case, the remainder of the finally block can’t execute anything that assumes success.

Similarly, one might be tempted to add code to act on wasInterrupted == true in some way, but tryCompleteWith could still beat tryFailure, right?

Adapting your code,

() => {
  var cancelled = false
  lock.synchronized {
    Option(updateCurrentThread(null)) foreach {
      _.interrupt()
     cancelled = p.failure(new CancellationException)
    }
  }
  cancelled
}

seems like a possible solution for avoiding the two interleavings described above (with some wrangling to retain the () => Boolean type).

@viktorklang

This comment has been minimized.

Copy link
Owner Author

@viktorklang viktorklang commented Jan 27, 2014

I've updated the code, to only report successful cancellation if both interruption AND completion is successful

@mtomy

This comment has been minimized.

Copy link

@mtomy mtomy commented Mar 20, 2015

This is the only way to cancel future I found :)

But I can't figure out how can I use interruptableFuture to stop composed futures? For example

val f = Future {
    // blocking interruptable computation
  }.map(res => {
    // one more blocking interruptable computation
  })

How can I cancel future f?

@minisaw

This comment has been minimized.

Copy link

@minisaw minisaw commented Mar 25, 2015

could you explain the point behind passing Future to fun:
"fun: Future[T] => T"

instead of having just:
"fun: => T"
?

@viktorklang

This comment has been minimized.

Copy link
Owner Author

@viktorklang viktorklang commented Apr 4, 2015

@minisaw Because when that Future is completed, the code knows that it has been interrupted, this is important in the case where the logic uses multiple threads underneath and you want to be able to propagate the interruption signal across them all (Thread.interrupted() is only for a single Thread.)

@Tolsi

This comment has been minimized.

Copy link

@Tolsi Tolsi commented Sep 11, 2015

I think that this implementation is not easy to use. And if call the 'cancel' method was before actual starting the task execution, then the task will not be canceled and will be executed. I tried to fix these moments here https://gist.github.com/Tolsi/1c81840b6f132b8f69c2

@viktorklang

This comment has been minimized.

Copy link
Owner Author

@viktorklang viktorklang commented Jun 28, 2016

@Tolsi You should introspect the Future provided to the function to determine whether you want to run or not.

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