Guava ListenableFuture

ListenableFuture, as its name implies, is a Future that can be monitored, which is an extension and enhancement of Java's native Future. We know that Future represents an asynchronous calculation task, and the calculation result can be obtained when the task is completed. If we want to get the results to show to the user once the calculation is completed or do other calculations, we must use another thread to continuously query the calculation status. In doing so, the code is complicated and inefficient. Use ListenableFuture
Guava to help us detect whether the Future is completed, and automatically call the callback function if it is completed, which can reduce the complexity of concurrent programs.
ListenableFuture is an interface that inherits from the Future interface of jdk and adds the void addListener(Runnable
listener, Executor executor) method.

Let's see how to use ListenableFuture. First, you need to define an instance of ListenableFuture.

       ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        final ListenableFuture<Integer> listenableFuture = executorService.submit(new Callable<Integer>() {
    
    
            @Override
            public Integer call() throws Exception {
    
    
                System.out.println("call execute..");
                TimeUnit.SECONDS.sleep(1);
                return 7;
            }
        });

First, initialize a ListeningExecutorService method through the static method listeningDecorator method of the MoreExecutors class, and then use the submit method of this instance to initialize the ListenableFuture object.

The work to be done by the ListenableFuture we defined above is defined in the implementation class of the Callable interface, here it just sleeps for 1 second and then returns a number 7.

With an instance of ListenableFuture, there are two ways to execute this Future and execute the callback function after the Future is completed.

Method 1: Through the addListener method of ListenableFuture

 listenableFuture.addListener(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                try {
    
    
                    System.out.println("get listenable future's result " + listenableFuture.get());
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                } catch (ExecutionException e) {
    
    
                    e.printStackTrace();
                }
            }
        }, executorService);

Method 2: Add a callback function to ListenableFuture through the static method addCallback of Futures

        Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {
    
    
            @Override
            public void onSuccess(@Nullable Integer result) {
    
    
                System.out.println("get listenable future's result with callback " + result);
            }

            @Override
            public void onFailure(Throwable t) {
    
    
                t.printStackTrace();
            }
        },executorService);

The second method is recommended, because the second method can directly get the return value of Future or handle error conditions. In essence, the second method is realized by mobilizing the first method and further encapsulated.

In addition, ListenableFuture has several other built-in implementations:

SettableFuture: There is no need to implement a method to calculate the return value, but only need to return a fixed value as the return value. The return value or exception information of this Future can be set by the program.
CheckedFuture:
This is an inherited from the ListenableFuture interface, which provides The checkedGet() method, this method can throw an exception of the specified type when an exception occurs in the execution of the Future.

Guess you like

Origin blog.csdn.net/GoSaint/article/details/107811039