I have a Java method that gets a value from a database table cell.
Let's name it jdbcTemplate.queryForObject()
I want to run this method once per 2 minutes until the value of the cell becomes true
.
Is it possible to achieve this using CompletableFuture?
No.
A CompletableFuture
is a mechanism for delivering a result from one thread to another. It doesn't have any functionality for computing things or repeating things.
A CompletableFuture
returns one value only. Once it has been "completed", the value cannot be changed. You can call complete
multiple times with different values, but they will be ignored according to the javadoc.
Of course, you could write some code that repeatedly queries the database, and only calls complete(...)
when the database cell becomes true. For example:
// Do this twice a minute until it succeeds.
if (jdbcTemplate.queryForObject()) {
future.complete(Boolean.TRUE);
// stop repeating ...
}
The idea is to call complete
just once to deliver a result ... and then terminate the loop or whatever that is repeating the query.
But that's not using CompletableFuture
to do the repeated queries.
Note: you should also consider cases such as the query taking too long, or failing with an exception.