Home > database >  How to effectively use isDone() in Future object
How to effectively use isDone() in Future object

Time:10-06

I created a java thread pool using

dbChangeService = Executors.newSingleThreadExecutor();

I have implemented a runnable interface and added it to

Future future = dbChangeService.submit(dbChgProcessor);

when I do future.isDone() it returns false which is understandable because I am checking immediately after submitting.

What is the correct way of using Future.isDone() method so that it can produce meaningful results.

PS: I don't want to use Future.get() which is a blocking call.

CodePudding user response:

Instead of simply doing future.isDone(), you should poll for it to be true. E.g.

while(!future.isDone()) 
{
 log.info("future not done yet, waiting before retrying...");
 Thread.sleep(300);
}
Object result = future.get();

This still is still kind of blocking, so you probably wanna do it on another thread that will notify your main tread using a lock object. Or even better why not use CompletableFuture? See resources here & here.

CodePudding user response:

So first of all let me clarify that:

Future.isDone() tells us if the executor has finished processing the task.

If the task is complete, it will return true otherwise, it returns false.

I would suggest you to use CompletableFuture, something like:

CompletableFuture.supplyAsync(() -> {
              ...
});

This will return a CompletableFuture as well.

As I said in the comments, a CompletableFuture provides a broad set of methods for creating multiple Futures, chaining, and combining. It also has comprehensive exception handling support

Check a full guide with CompletableFuture examples here

  • Related