Suppose I have a blocking method called check
as follows:
boolean check(String input) {}
which will do some check against the input and return the decision.
Now I want to run this check against a list of inputs asynchronously, and I want to return to the main thread right after one of the inputs passing the check, so I don't have to wait for all asynchronous call to be completed. The only one scenario for waiting all threads to complete is that there are no inputs passing the check. Running the method asynchronously with list of inputs is straightforward but I'm not sure how to return to the main thread after getting the target output for the input passing the check.
The simplest way to execute a method asynchronously is to start executing the method by calling the delegate's BeginInvoke method, do some work on the main thread, and then call the delegate's EndInvoke method. EndInvoke might block the calling thread because it does not return until the asynchronous call completes.
Simply put, annotating a method of a bean with @Async will make it execute in a separate thread. In other words, the caller will not wait for the completion of the called method. One interesting aspect in Spring is that the event support in the framework also has support for async processing if necessary.
Here is a really simple working example to achieve what you are asking for
Future<Boolean> future = CompletableFuture.runAsync(() -> {
// Do your checks, if true, just return this future
System.out.println("I'll run in a separate thread than the main thread.");
});
// Now, you may want to block the main thread waiting for the result
while(!future.isDone()) {
// Meanwhile, you can do others stuff
System.out.println("Doing other stuff or simply waiting...");
}
// When future.isDone() returns, you will be able to retrieve the result
Boolean result = future.get();
A basic parallelStream will do exactly that:
boolean match = inputs.parallelStream().anyMatch(input -> check(input));
Returns early with match==true
, iff some input is found that matches check
.
match
will be false if all inputs are checked and none matched.
In the standard case it will use the fork/join thread pool. But with some further effort you can avoid that.
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