为什么Scala的Future没有.get/get(maxDuration)方法,迫使我们诉诸Await.result()? [英] Why doesn't Scala's Future have a .get / get(maxDuration) method, forcing us to resort to Await.result() instead?

查看:77
本文介绍了为什么Scala的Future没有.get/get(maxDuration)方法,迫使我们诉诸Await.result()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

get方法与Future类(我希望它驻留在其中)分离,并迫使编码器必须了解这个称为Await?

Is there any particular advantage in decoupling the get method from the Future class (where I'd expect it to reside) and to instead force the coder to have to know about this external two-method class called Await?

推荐答案

get方法与Future类解耦是否有任何特殊优势

Is there any particular advantage in decoupling the get method from the Future class

是的,这会使开发人员难以完成错误的事情. Future表示将在将来完成并且在当前调用点可能不可用的计算.如果您需要阻止未来,为什么不同步执行呢?在线程池上调度它,浪费一个完美的线程池线程有什么意义呢?

Yes, to make it difficult for the developer to do the wrong thing. A Future represents a computation which will complete in the future and might not be available at the current invocation point. If you need to block a future, why not execute it synchronously? Whats the point of scheduling it on the threadpool, wasting a perfectly good threadpool thread?

文档说:

超越未来

如前所述,强烈建议不要为将来而阻塞,以实现性能并防止死锁.期货的回调和组合器是使用其结果的首选方法.但是,在某些情况下屏蔽可能是必要的,并且由Futures and Promises API支持.

Blocking outside the Future

As mentioned earlier, blocking on a future is strongly discouraged for the sake of performance and for the prevention of deadlocks. Callbacks and combinators on futures are a preferred way to use their results. However, blocking may be necessary in certain situations and is supported by the Futures and Promises API.

甚至 Await对象文档:

And even the Await object documentation:

虽然偶尔有用,例如对于测试,建议您尽可能避免使用Await,而希望使用诸如onComplete之类的回调和组合器,并使用in进行理解. Await将阻塞其运行的线程,并可能导致性能和死锁问题.

While occasionally useful, e.g. for testing, it is recommended that you avoid Await when possible in favor of callbacks and combinators like onComplete and use in for comprehensions. Await will block the thread on which it runs, and could cause performance and deadlock issues.

您可以看到语言设计者有意要这种效果.

You can see that the language designers intentionally wanted this effect.

这篇关于为什么Scala的Future没有.get/get(maxDuration)方法,迫使我们诉诸Await.result()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆