cAMPy
cAMPy

Reputation: 587

Java awaiting Future result without blocking

I have an application where by clicking buttons (that number is defined) user creates tasks (Callable) that do some calculations. I want to be able to react when the task is finished. Using Future.get() blocks the application. Is there any way to be able to react when the Callable returns the result?

private static void startTask(int i){
    try{
        Future<Integer> future = executor.submit(callables.get(i-1));
        ongoingTasks.put(i, future);
        awaitResult(future, i);
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

private static void awaitResult(Future<?> future, int taskNo) throws InterruptedException, ExecutionException{
    System.out.println("result : " + future.get());

    JButton b = buttons.get(taskNo);
    b.setEnabled(false);
}

Upvotes: 1

Views: 2272

Answers (1)

Michael
Michael

Reputation: 44090

It sounds like you want a CompletableFuture. You have a function which is a "supplier" which supplies a value. This is the function that's actually doing the work.

You then have a function which accepts that value whenever the worker is done.

This is all asynchronous, so everything else carries on regardless of the outcome.

class Main
{
    private static Integer work() {
        System.out.println("work");
        return 3;
    }

    private static void done(Integer i) {
        System.out.println("done " + i);
    }

    public static void main (String... args)
    {
        CompletableFuture.supplyAsync(Main::work)  
                         .thenAccept(Main::done);

        System.out.println("end of main");
    }
}

Sample output:

end of main
work
done 3

Upvotes: 3

Related Questions