javaspringspring-cachecompletable-futurespring-async

Spring @Cacheable and @Async annotation


I have the need to cache some the results of some asynchronous computations. In detail, to overcome this issue, I am trying to use Spring 4.3 cache and asynchronous computation features.

As an example, let's take the following code:

@Service
class AsyncService {
    @Async
    @Cacheable("users")
    CompletableFuture<User> findById(String usedId) {
        // Some code that retrieves the user relative to id userId
        return CompletableFuture.completedFuture(user);
    }
}

Is it possible? I mean, will the caching abstraction of Spring handle correctly the objects of type CompletableFuture<User>? I know that Caffeine Cache has something like that, but I can't understand if Spring uses it if properly configured.

EDIT: I am not interested in the User object itself, but in the CompletableFuture that represents the computation.


Solution

  • As per SPR-12967, ListenableFuture (CompletableFuture) are not supported.