0

I am learning Java Future API. I want to write a generic Future handler code that gets any value from a Future and passes it to a callback function. To elaborate, if below is a generic function that handles Future objects:

private static <T> void genericFutureHandler(List<Future<T>> futures, CompletionAction completionAction) throws InterruptedException {
  for (Future<T> f : futures) {
    if (f.isDone()) {
       try {
         T iter = f.get();
         completionAction.showCompletedTaskNumber(iter);
       } catch (ExecutionException e) {
         e.printStackTrace();
       }
   }
}

I want my callback to be like:

class TaskStatusCompletionAction implements CompletionAction {

    @Override
    public void showCompletedTaskNumber(int taskNumber) {
        System.out.println("Task number : "+taskNumber+" completed");
    }
}

interface CompletionAction {
    void showCompletedTaskNumber(int taskNumber);
}

How can I write/design code that transparently handles all future objects, gets their completed value and hands if off to the provided callback? Is anything like that possible or I am asking wrong question?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shades88
  • 7,934
  • 22
  • 88
  • 130
  • 2
    Have a look at `CompletableFuture`. – Jean-Baptiste Yunès Aug 31 '23 at 14:40
  • Your sketch will block until all tasks are complete. Is that what you want? If so, what is the point of submitting a task and getting a `Future` in the first place? You could just run the tasks yourself in the current thread. – erickson Aug 31 '23 at 15:09
  • I believe the second example (using `CompletableFuture`) I gave [in my answer here](https://stackoverflow.com/a/826283/3474) does what you want. If your question is different, please edit to distinguish it from the proposed duplicate, reply to me, and we can re-open. – erickson Aug 31 '23 at 15:13

0 Answers0