Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling two functions in parallel in Java 8

I have a use case in my Spring boot application as follows:

I would like to fetch the id field value from the response with the following function:

String id = getIdFromResponse(response);

If I don't get any id in the response, then I check if the id field is present in the request argument with the following function:

String id = getIdFromRequest(request);

As of now, I am invoking them sequentially. But I would like to make these two functions run parallelly, I would like to stop as soon as I get an id from either of them.

I am wondering if there is any way to implement this using streams in Java 8.

like image 356
Joy Avatar asked Oct 21 '20 06:10

Joy


Video Answer


1 Answers

You can use something like this:

String id = Stream.<Supplier<String>>of(
        () -> getIdFromResponse(response), 
        () -> getIdFromRequest(request)
    )
    .parallel()
    .map(Supplier::get)
    .filter(Objects::nonNull)
    .findFirst()
    .orElseThrow():

The suppliers are needed, because when you don't use them, then both requests are still executed sequentially.

I also assumed that your methods return null when nothing is found, so I had to filter these values out with .filter(Objects::nonNull).

Depending on your use case, you can replace .orElseThrow() with something different, like .orElse(null)

like image 90
Lino Avatar answered Sep 25 '22 09:09

Lino