Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement non blocking Futures in Java

The Java Future object is used to get the result of asynchronous computation which is performed by a parallel thread(Executors). We call Future.get() method and wait until result is ready. This example shows a non blocking way for retrieving result from Future. java-implement-java-non-blocking-futures.

NonBlockingExecutor executor = new NonBlockingExecutor(Executors.newSingleThreadExecutor());

NonBlockingFuture<Integer> future = executor.submitNonBlocking(new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {
                String threadName = Thread.currentThread().getName();
                System.out.println(threadName);
                //print -> pool-1-thread-1
                return 1;
            }
});

future.setHandler(new FutureHandler<Integer>() {

       @Override
       public void onSuccess(Integer value) {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName);
            //print -> pool-1-thread-1
       }

       @Override
       public void onFailure(Throwable e) {
            System.out.println(e.getMessage());
       }
 });

 Thread.sleep(50000);

In this onSuccess() method is called after parallel execution is finish. The problem is onSuccess() method is not running on the main thread. I want to perform onSuccess() method on the main thread. How can i fix this. Thanks

like image 465
Tharanga Avatar asked Dec 14 '22 06:12

Tharanga


1 Answers

This is supported with CompletableFutures.

    CompletableFuture.runAsync(() -> {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName);
        //print -> pool-1-thread-1
    }).whenComplete((task, throwable) -> {
        if(throwable != null) {
           System.out.println(e.getMessage());
        } else {
            String threadName = Thread.currentThread().getName();
            System.out.println(threadName);
            //print -> pool-1-thread-1
        }
    });

The caveat here is that the future would run the whenComplete task on the executing thread and not the submitting thread.

like image 58
John Vint Avatar answered Dec 17 '22 02:12

John Vint