Can I repeat method using CompletableFuture until value is true

Viewed 364

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?

2 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. But that's not using CompletableFuture to do the repeated queries.

you can use this working example:

    CompletableFuture<Object> future = new CompletableFuture<>();


    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            try {
                Object o = "jdbcTemplate.queryForObject()";
                if (o != null) {
                    future.complete(o);
                }
            } catch (Exception ex) {
                future.completeExceptionally(ex);
            }
        }
    }, 0, 1000*2*60);
    System.out.println("checking database periodically ran");
    future.thenAccept(o -> {
        System.out.println(o);
        timer.cancel();
    }).join();
Related