I want to parallelize the following code snipped using a parallelStream:
boolean anyTrue() {
for (Element e : setOfE) {
if (eval(e)) {
return true;
}
}
return false;
}
Will the following work on parallel streams and use regular short-circuit evaluation?
setOfE.parallelStream().map(e -> eval(e)).reduce(false, (a,b) -> a || b))
Boolean values and operationsConstant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0. The following table shows comparisons and boolean operations.
The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string "true" . Example: Boolean.
In the boolean type, there are only two possible values: true and false. We can have variables and expressions of type boolean, just has we have variables and expressions of type int and double. A boolean variable is only capable of storing either the value true or the value false.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Streams API actually has first-class support for your requirement:
setOfE.parallelStream().anyMatch(e -> eval(e));
As opposed to your approach with reduce
, this is guaranteed to have short-circuit evaluation and optimally leverage parallelism.
No, reduction does not support short-circuit evaluation. The reason is that reduce
just receives an arbitrary BinaryOperator
implementation and has no idea about the possibilities of short-circuiting the particular operation.
But you can perform the entire operation much simpler:
setOfE.parallelStream().filter(e -> eval(e)).findAny().isPresent()
This simply searches for an arbitrary item for which eval
returns true
and findAny
allows to end the operation as soon as one thread has encountered a match. The resulting Optional
can be queried for being empty as you are not interested in the particular matching Element
.
Alternatively you can use as suggested by Marko Topolnik’s comment:
setOfE.parallelStream().anyMatch(e -> eval(e))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With