-5

Okay, working with Java 8, need to know if my code below does what I need it to do.

  • I have three methods. Each do an operation and return success or failure as a boolean.
  • I need to have all three operate at the same time.
  • If any return a false, the first one to do so will cause the entire process to short-circuit and the master method to return a false.
  • If none of them return a false, all three need to run to completion and return a true for the master method to return a true.

My code:

private boolean checkProcess1(){
    //does stuff, mostly DB schema checking
}

private boolean checkProcess2(){
    //does stuff, mostly queries on a different DB
}

private boolean checkProcess3(){
    //does stuff, checking files and versioning
}

public boolean checkProcessesForSuccess(){
    final List<Supplier<Boolean>> checkList = Arrays.asList(
        this::checkProcess1,
        this::checkProcess2,
        this::checkProcess3
    );
    return checkList.parallelStream().allMatch( Supplier :: get );
}

My main sticking point concerns the .allMatch(). It is supposed to take a predicate that determines how each item in the list is evaluated. By passing in the Supplier :: get, does it not return a true on any full set of matches, such as all false values, or does it require all values to be true in order to return a true?

Additionally, if the first method to return a result is false, does this short-circuit the entire master method, or does it continue processing until all three are complete? My worry is that if a short-running method returns a false, the entire system will be bound by the longest-running method.

I had previously tried to utilize CompletableFuture for this problem, and I did come up with a solution, but it was quite a bit more complex and - honestly - quite inelegant and ugly. I turned to Streams in an attempt to see if the problem could be resolved in a simpler and more elegant manner.

Suggestions?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
R. Kåbis
  • 51
  • 7

1 Answers1

2

By passing in the Supplier :: get, does it not return a true on any full set of matches, such as all false values, or does it require all values to be true in order to return a true?

It requires all supplier.get to return true to eventually return true as a complete result from checkProcessesForSuccess.

Additionally, if the first method to return a result is false, does this short-circuit the entire master method, or does it continue processing until all three are complete?

It does short-circuit, as mentioned in the javadoc.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • 2
    It does short-circuit, but for a stream of three elements, chances are high that a parallel stream already commenced all operations by the time the first returns. So it will likely return only when all of them completed. There’s no way around this. Either, you have them parallel or you have not… – Holger Feb 03 '20 at 12:48