I started working with CompletableFuture
in Spring Boot, and I'm seeing in some places that the usual repository methods return CompletableFuture <Entity>
instead of Entity
.
I do not know what is happening, but when I return instances of CompletableFuture
in repositories, the code runs perfectly. However when I return entities, the code does not work asynchronously and always returns null
.
Here is an example:
@Service
public class AsyncServiceImpl{
/** .. Init repository instances .. **/
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public CompletableFuture<Token> getTokenByUser(Credential credential) {
return userRepository.getUser(credential)
.thenCompose(s -> TokenRepository.getToken(s));
}
}
@Repository
public class UserRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public CompletableFuture<User> getUser(Credential credentials) {
return CompletableFuture.supplyAsync(() ->
new User(credentials.getUsername())
);
}
}
@Repository
public class TokenRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public CompletableFuture<Token> getToken(User user) {
return CompletableFuture.supplyAsync(() ->
new Token(user.getUserId())
);
}
}
The previous code runs perfectly but the following code doesn't run asynchronously and the result is always null
.
@Service
public class AsyncServiceImpl {
/** .. Init repository instances .. **/
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public CompletableFuture<Token> requestToken(Credential credential) {
return CompletableFuture.supplyAsync(() -> userRepository.getUser(credential))
.thenCompose(s ->
CompletableFuture.supplyAsync(() -> TokenRepository.getToken(s)));
}
}
@Repository
public class UserRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_REPOSITORY)
public User getUser(Credential credentials) {
return new User(credentials.getUsername());
}
}
@Repository
public class TokenRepository {
@Async(AsyncConfiguration.TASK_EXECUTOR_SERVICE)
public Token getToken(User user) {
return new Token(user.getUserId());
}
}
Why doesn't this second code work?