Suppose I have a future result, let's call it garfield
def garfield = Future{
Thread.sleep(100)
System.currentTimeMillis()
}
I can run garfield
concurrently with in for comprehension
like this
val f1 = garfield
val f2 = garfield
for {
r1 <- f1
r2 <- f2
} yield r1 -> r2
as explained in this answer.
Suppose I don't want to polluting the local scope with future variables if I won't need them later. Is this a valid alternative approach?
for {
f1 <- Future{garfield}
f2 <- Future{garfield}
r1 <- f1
r2 <- f2
} yield r1 -> r2
Edit
It appears my original approach, using Future.apply
includes overhead that most of the time causes sequential execution, see example.
Using the alternative approach
for {
f1 <- Future.successful(garfield)
f2 <- Future.successful(garfield)
r1 <- f1
r2 <- f2
} yield r1 -> r2
behaves as expected.
Then again, this approach is a bit odd and perhaps a more conventional approach of scoping the futures in a Unit
is preferred.
val res = {
val f1 = garfield
val f2 = garfield
for {
r1 <- f1
r2 <- f2
} yield r1 -> r2
}
I'm curios if someone could shed some more light on the reason for the sporadic lack of concurrent execution.