我的play应用程序中有一个角色,它的每一个刻度(2秒)都会向某个方法发送一条消息:
onSomething() : Future[Unit] = {
for {
a <- somethingThatReturnsFuture
b <- anotherThingThatReturnsFuture
}
}这个方法有两个返回future的调用,所以我决定使用for-comprehension,但是for-comprehension阻塞了吗?所以akka不能再次调用这个方法,即使他们运行了16个实例,直到方法完成?
如果我有我的方法来处理flatMap/map,这会让akka有更好的性能吗?如下所示:
onSomething() : Future[Unit] = {
somethingThatReturnsFuture.flatMap(res1 => {
anotherThingThatReturnsFuture.map(res2 => {
//whatever
})
})
}谢谢
发布于 2020-03-09 23:13:03
根据Luis的评论,for-只是语法糖
Scala的“用于理解”是使用
foreach、map、flatMap、filter或withFilter组合多个操作的语法糖。Scala实际上将for-expression转换为对这些方法的调用,因此提供它们的任何类或它们的子集都可以与for comprehensions一起使用。
它扩展到底层的一元操作,因此应该不会对直接使用一元操作的性能造成影响。如果您的方法是相互独立的,那么可以通过利用Future是的渴望来获得相同的性能,并像这样在for- independent之外启动它们。
val aF = somethingThatReturnsFuture()
val bF = anotherThingThatReturnsFuture() // I started without waiting on anyone
for {
a <- aF
b <- bF
} yield {
a + b
}但是,如果b的计算依赖于a,那么您将无法并行地启动它们
for {
a <- somethingThatReturnsFuture
b <- anotherThingThatReturnsFuture(a)
} yield {
a + b
}在这里,anotherThingThatReturnsFuture在必须等待somethingThatReturnsFuture的意义上“阻塞”。
发布于 2020-03-09 23:03:55
首先。因为您正在调用的方法返回一个Future,所以它们都不会阻塞Thread的执行。
但事实是,平面映射将按顺序连接这两个操作。我的意思是,它将调用第一个方法,然后立即返回,因为它是一个Future,然后它将调用第二个方法。
这将发生在你之前发布的两个选项中(用于理解和扁平图),因为它们基本上是相同的。
如果你想同时调用这两个方法(在两个不同的线程中),所以你不知道哪一个会先开始执行,你必须使用并行集合。
但在您的情况下,最好不要使用它们,因为使用期货可以保证线程不会阻塞。
https://stackoverflow.com/questions/60602507
复制相似问题