multithreading - Means for performing background operations in Scala -
i'd time consuming task in background. need start computation in different thread, able check if completed (maybe failed) , able abort computation when becomes unnecessary. after computation ended should call synchronized callback function store computed value.
it may programmed wrapper on thread class. suppose basic functionality implemented in scala library already. i've tried search find akka simple task. scala.concurrent.executioncontext
has useful execute
method return no object check status of computation , abort on demand.
what library contains described functionality?
i've checked scala.concurrent.future
. lacks ability abort computation, crucial. use following strategy: compute consuming function in background , provide reasonable default. if arguments function changed, drop original computation , start new. not imagine how rewrite strategy in terms of future.flatmap.
i'll give demonstration of how use futures twitter's implementation, since asked cancellation:
import com.twitter.util.{ await, future, futurepool } def computefast(i: int) = { thread.sleep(1000); + 1 } def computeslow(i: int) = { thread.sleep(1000000); + 1 } val fastcomputation = futurepool.unboundedpool(computefast(1)) val slowcomputation = futurepool.unboundedpool(computeslow(1))
now can poll result:
scala> fastcomputation.poll res0: option[com.twitter.util.try[int]] = some(return(2)) scala> slowcomputation.poll res1: option[com.twitter.util.try[int]] = none
or set callbacks:
fastcomputation.onsuccess(println) slowcomputation.onfailure(println)
most of time it's better use map
, flatmap
describe how compose computations, though.
cancellation little more complicated (this demo—you'll want provide own cancellation logic):
import com.twitter.util.promise def cancellablecomputation(i: int): future[int] = { val p = promise[int] p.setinterrupthandler { case t => println("cancelling computation") p.setexception(t) } futurepool.unboundedpool(computeslow(i)).onsuccess(p.setvalue) p }
and then:
scala> val myfuture = cancellablecomputation(10) myfuture: com.twitter.util.future[int] = promise@129588027(state=interruptible(list(),<function1>)) scala> myfuture.poll res4: option[com.twitter.util.try[int]] = none scala> myfuture.raise(new exception("stop thing")) cancelling computation scala> myfuture.poll res6: option[com.twitter.util.try[int]] = some(throw(java.lang.exception: stop thing))
you similar standard library's futures.
Comments
Post a Comment