Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I repeat method using CompletableFuture until value is true

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?

like image 244
bohdan Avatar asked Feb 20 '26 15:02

bohdan


1 Answers

No.

  1. 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.

  2. 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.

like image 199
Stephen C Avatar answered Feb 23 '26 07:02

Stephen C