Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java asynchronously call a method for target output

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.

like image 410
Jiahui Zhang Avatar asked Jun 09 '20 23:06

Jiahui Zhang


People also ask

How do you call a method asynchronously?

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.

What does @async annotation do?

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.


Video Answer


2 Answers

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();
like image 169
Snix Avatar answered Oct 18 '22 03:10

Snix


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.

like image 39
k5_ Avatar answered Oct 18 '22 03:10

k5_