简体   繁体   English

在Scala的期货中使用期货的方法

[英]Way to use Futures inside Futures in Scala

I need to perform thousands of tasks simultaneously. 我需要同时执行数千个任务。 So i am thinking of using Futures for this purpose. 所以我正在考虑为此目的使用期货。 But each of these thousands tasks are already in Future. 但是这数千个任务中的每一个都已经在未来。 Is it good to use future inside future. 在未来中使用未来会很好。 Or i am doing something wrong here. 或者我在这里做错了。 Each task takes approx 1 ms time to compute. 每个任务大约需要1毫秒的时间来计算。 So instead of performing them sequentially i think it is preferable to do in futures. 因此,我认为最好不要在期货交易中按顺序进行。 So theoretically it should take approx 1 ms or somewhere around that to complete entire task. 因此,从理论上讲,完成整个任务大约需要1毫秒左右。 But complete execution is taking 150 ms. 但是完整的执行需要150毫秒。 So does that mean all parallel tasks are taking more than what it is taking individually. 这是否意味着所有并行任务所承担的工作要比单独承担的任务多。

val start = System.nanoTime()

You can use the flatMap() function on futures to compose them, which I guess is what you call "futures inside futures", and it's a great idiomatic way to use futures. 您可以在期货上使用flatMap()函数进行组合,我想这就是您所说的“期货内的期货”,这是使用期货的一种很好的惯用方式。

Map express "with the result of this future, trigger this one". 地图表示“用这个未来的结果,触发这个”。 For example you could do something like getASpecificEndpointInDb().flatMap(endpointURL => doAGetRequest(endpointURL)) where getASpecificEndpointInDb() returns a Future[String] and doAGetRequest() returns a Future[JsObject] 例如,您可以执行类似getASpecificEndpointInDb().flatMap(endpointURL => doAGetRequest(endpointURL)) ,其中getASpecificEndpointInDb()返回Future [String],而doAGetRequest()返回Future [JsObject]

To answer the second part of your question : even if you have 1000 parallel tasks, your computer can only physically process a small number at any given time. 要回答问题的第二部分:即使您有1000个并行任务,您的计算机在任何给定时间都只能物理处理少量任务。 Depending on your machine, if it's, let's say 8, the best it can achieve theorically is then 1000/8 = 125 ms. 假设您使用的是8,具体取决于您的计算机,则理论上可以达到的最佳效果是1000/8 = 125 ms。 But as there are some context switching costs, 150ms is totally reasonable. 但是由于存在一些上下文切换成本,因此150ms是完全合理的。 And still a lot better than 1000ms if doing it sequentially :) 如果顺序执行,仍然比1000ms好得多:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM