延期,承诺和期货有什么区别?
这三者背后是否有普遍认可的理论?
Future和之间有什么区别Promise?
它们都像未来结果的占位符,但主要区别在哪里?
我把自己与未来和承诺之间的区别混淆了.
显然,他们有不同的方法和东西,但实际的用例是什么?
是吗?:
我有一个返回List期货的方法
List<Future<O>> futures = getFutures();
Run Code Online (Sandbox Code Playgroud)
现在我想要等到所有期货都成功处理完成,或者将来输出的任何任务抛出异常.即使一个任务抛出异常,也没有必要等待其他期货.
简单的方法是
wait() {
For(Future f : futures) {
try {
f.get();
} catch(Exception e) {
//TODO catch specific exception
// this future threw exception , means somone could not do its task
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是,例如,如果第四个未来抛出异常,那么我将不必要地等待前3个期货可用.
怎么解决这个?会以任何方式倒数闩锁帮助吗?我无法使用Future,isDone因为java doc说
boolean isDone()
Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true.
Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法将Futures的任意长度列表转换为List of Future.我正在使用Playframework,所以最终,我真正想要的是Future[Result],但为了简化,我们只是说Future[List[Int]]这样做的正常方法是使用Future.sequence(...)但是有一个扭曲......我给出的列表通常有其中约有10-20个期货,其中一个期货失败并不常见(它们正在制作外部网络服务请求).在其中一个失败的情况下,我不想重试所有这些,而是希望能够获得那些成功的并返回那些.
例如,执行以下操作不起作用
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure
val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) ::
Future.successful(3) :: Nil
val futureOfList = Future.sequence(listOfFutures)
futureOfList onComplete {
case Success(x) => println("Success!!! " + x)
case Failure(ex) => println("Failed !!! " + ex)
}
scala> Failed !!! java.lang.Exception: Failure
Run Code Online (Sandbox Code Playgroud)
我没有得到唯一的例外,而是希望能够将1和3拉出来.我尝试过使用Future.fold,但显然只是Future.sequence在幕后调用.
在此先感谢您的帮助!
期货和承诺都会阻止,直到他们计算出它们的价值,那么它们之间有什么区别呢?
假设我有几个期货,需要等到其中任何一个失败或全部成功.
例如:我们有3个期货:f1,f2,f3.
如果f1成功并f2失败,我不等待f3(并将失败返回给客户端).
如果f2失败f1而且f3仍然在运行,我不等待它们(并返回失败)
如果f1成功然后f2成功我会继续等待f3.
你会如何实现它?
Java 8引入CompletableFuture了一个可组合的Future的新实现(包括一堆thenXxx方法).我想独占使用它,但我想使用的许多库只返回不可组合的Future实例.
有没有办法将返回的Future实例包装在一个内部,CompleteableFuture以便我可以编写它?
Scala的期货线程池有多大?
我的Scala应用程序创建了数百万future {}s,我想知道我是否可以通过配置线程池来优化它们.
谢谢.
在Java中构建完整未来的最佳方法是什么?我已经CompletedFuture在下面实现了自己,但希望这样的东西已经存在.
public class CompletedFuture<T> implements Future<T> {
private final T result;
public CompletedFuture(final T result) {
this.result = result;
}
@Override
public boolean cancel(final boolean b) {
return false;
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
@Override
public T get() throws InterruptedException, ExecutionException {
return this.result;
}
@Override
public T get(final long l, final TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
return get();
}
}
Run Code Online (Sandbox Code Playgroud) future ×10
java ×4
promise ×4
scala ×3
concurrency ×2
c++ ×1
c++11 ×1
clojure ×1
deferred ×1
java-8 ×1
javascript ×1
terminology ×1
threadpool ×1