Java8 CompletedFuture conditional chain

I read a lot of java8 ready-made future tutorials, most of them are basically the same. Everyone is talking about some basic method thenAccept / thenApply / thenCombine for building a pipeline stream.

But when you are faced with a real work problem, it is difficult for me to organize different final futures from different services. For instance:

    interface Cache{
       CompletableFuture<Bean> getAsync(long id);
       CompletableFuture<Boolean> saveAsync(Bean bean);
    }


   interface DB{
       Completable<Bean> getAsync(long id)
    }

the maintenance logic is quite simple, get data from the cache, if there is a return to our client, if not, get it from the database, if it exists, save it back to the Cache and return it to our client if the database does not exist, return an "error "to the customer.

using API synchronization, it will be pretty straight forward. But when using the asynchronous API, there are "many pipelines", a muddy conditional break. I cannot figure out how to implement this using the CompletingFuture API.

+4
source share
1 answer

If you do not care about the result of saving to the cache, and if you want to throw an exception from the bean, then it can be, for example,

CompletableFuture<Bean> findBeanAsync(long id, Cache cache, DB db) {
    return cache.getAsync(id).thenCompose(bean -> {
        if (bean != null) {
            return CompletableFuture.completedFuture(bean);
        }
        return db.getAsync(id).thenApply(dbBean -> {
            if (dbBean == null) {
                throw new RuntimeException("bean not found with id " + id);
            }
            cache.saveAsync(dbBean);
            return dbBean;
        });
    });
}
+6
source

Source: https://habr.com/ru/post/1672315/


All Articles