I take a List[Int]
and want to search for a value x
where x * 10 > 500
in parallel. So exists
should return true
if the list contains any value of 51 or greater.
def f(x: Int) = {
println("calculating for " + x)
Thread.sleep(100 - x)
println("finished " + x)
x * 10
}
val res = List.range(1, 100).par.exists(f(_) > 500)
Which gives results:
calculating for 1
calculating for 25
calculating for 50
calculating for 75
calculating for 13
finished 75 // <-- first valid result found: 75 * 10 > 500
finished 50
calculating for 51 // but it kicks off more expensive calculations
finished 25
calculating for 26
finished 13
calculating for 14
finished 1
calculating for 2
finished 51
finished 26
calculating for 27 // and more
finished 14
calculating for 15
finished 2
calculating for 3
finished 27
calculating for 28
finished 15
calculating for 16
finished 3
calculating for 4 // and more...
finished 28
calculating for 29
finished 16
calculating for 17
finished 29
calculating for 30
finished 4
calculating for 5
finished 17
calculating for 18
finished 30
finished 5
calculating for 6
finished 18
finished 6
res: Boolean = true
I am using a dual-core machine with Scala 2.9.1.
What's going on here? Is this working as intended? Why doesn't it just send out the message to the other threads to abort mission as soon as the first result is found? This could be quite costly if f
is an expensive computation.
find
seems to work in a similar way, searching many more values, even though the docs say that the "element may not necessarily be the first such element in the iteration order" and "the choice is nondeterministic".