Twitter The timeout of the future does not apply to the entire flatMap chain.

I am writing a server end program using Twitter Finagle. I do not use the full Twitter server stack, just the part that allows asynchronous processing (so that future, function, etc.). I want Future objects to have timeouts, so I wrote the following:

Future<String> future = Future.value(some_input).flatMap(time_consuming_function1);
future.get(Duration.apply(5, TimeUnit.SECONDS));

time_consuming_function1works more than 5 seconds. But it futuredoes not expire after 5 seconds and waits until time_consuming_function1it finishes.

I think this is due to the fact that it future.get(timeout)only cares about how long futureit took to create, and not the entire chain of operations. Is there a way to timeout the entire chain of operations?

+5
source share
1 answer

, map/flatMap , .

, Future.value(some_input), flatMap , get . , . :

import scala.concurrent.ops._
import com.twitter.conversions.time._
import com.twitter.util.{Future,Promise}

val p = new Promise[String]
val longOp = (s: String) => { 
  val p = new Promise[String]
  spawn { Thread.sleep(5000); p.setValue("Received: " + s) }
  p 
}
val both = p flatMap longOp
both.get(1 second)  // p is not complete, so longOp hasn't been called yet, so this will fail
p.setValue("test")  // we set p, but we have to wait for longOp to complete
both.get(1 second)  // this fails because longOp isn't done
both.get(5 seconds)  // this will succeed
+1

All Articles