Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You only get timeout behavior when you use blocking to get the results of the <code>Future</code>. If you want to use the non-blocking callbacks <code>onComplete</code>, <code>onSuccess</code> or <code>onFailure</code>, then you would have to roll your own timeout handling. Akka has built in timeout handling for request/response (<code>?</code>) messaging between actors, but not sure if you want to start using Akka. FWIW, in Akka, for timeout handling, they compose two <code>Futures</code> together via <code>Future.firstCompletedOf</code>, one which represents the actual async task and one that represents the timeout. If the timeout timer (via a <code>HashedWheelTimer</code>) pops first, you get a failure on the async callback.</p> <p>A very simplified example of rolling your own might go something like this. First, an object for scheduling timeouts:</p> <pre><code>import org.jboss.netty.util.{HashedWheelTimer, TimerTask, Timeout} import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration import scala.concurrent.Promise import java.util.concurrent.TimeoutException object TimeoutScheduler{ val timer = new HashedWheelTimer(10, TimeUnit.MILLISECONDS) def scheduleTimeout(promise:Promise[_], after:Duration) = { timer.newTimeout(new TimerTask{ def run(timeout:Timeout){ promise.failure(new TimeoutException("Operation timed out after " + after.toMillis + " millis")) } }, after.toNanos, TimeUnit.NANOSECONDS) } } </code></pre> <p>Then a function to take a Future and add timeout behavior to it:</p> <pre><code>import scala.concurrent.{Future, ExecutionContext, Promise} import scala.concurrent.duration.Duration def withTimeout[T](fut:Future[T])(implicit ec:ExecutionContext, after:Duration) = { val prom = Promise[T]() val timeout = TimeoutScheduler.scheduleTimeout(prom, after) val combinedFut = Future.firstCompletedOf(List(fut, prom.future)) fut onComplete{case result =&gt; timeout.cancel()} combinedFut } </code></pre> <p>Note that the <code>HashedWheelTimer</code> I am using here is from Netty.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload