Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Future to Mono

I have legacy code which returns convert java.util.concurrent.Future, now I am supposed to wrap this method call in a layer which returns reactor publishers Mono or Flux. I believe approach to convert to either of them should be similar so what is the correct way to convert it to Mono.

Suppose for example I am getting Future from API and I need Mono

like image 708
dvsakgec Avatar asked Apr 07 '26 06:04

dvsakgec


1 Answers

Given that getting the result from a Future is always going to be blocking, a possible solution would be move that computation to a blocking-friendly scheduler.

 Mono.fromCallable(() -> {
        try {
            Future future = null;
            return future.get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
 }).subscribeOn(Schedulers.boundedElastic());

You can verify that your code is effectively non-blocking by using BlockHound https://github.com/reactor/BlockHound

like image 80
Johan Perez Avatar answered Apr 08 '26 21:04

Johan Perez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!