sta*_*wer 5 java twitter scala future finagle
我正在使用Twitter Finagle编写服务器端程序.我不使用完整的Twitter服务器堆栈,只是启用异步处理的部分(所以Future,Function等).我希望Future对象有超时,所以我写了这个:
Future<String> future = Future.value(some_input).flatMap(time_consuming_function1);
future.get(Duration.apply(5, TimeUnit.SECONDS));
Run Code Online (Sandbox Code Playgroud)
time_consuming_function1运行时间超过5秒.但是future5秒后没有超时,它等到time_consuming_function1完成.
我认为这是因为future.get(timeout)只关心future创建需要多长时间,而不是整个运营链.有没有办法超时整个运营链?
基本上,如果您在满意的 Future 上调用 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
Run Code Online (Sandbox Code Playgroud)