1. 程式人生 > >Guava併發程式設計之ListenableFuture類

Guava併發程式設計之ListenableFuture類

1 Future介面的缺點

通過Future介面的get()方法可以獲取類Callable的返回值,但是此方法最大缺點是阻塞的,因此在併發環境下,效率比較低。Google公司提供的開源Guava庫提供了有效的處理非同步Future的問題。

2 addListener()方法

Guava包的ListenableFuture實現了Future介面, 其原始碼如下:

public interface ListenableFuture<V> extends Future<V> {
     void addListener(Runnable listener, Executor executor);
}

addListener(Runnable listener, Executor executor)方法是非同步的,它註冊了一個監聽器,當Callable類執行結束,後會進入Runnable介面的實現類中。

public class MyCallable implements Callable<String> {
    private String name;

    public MyCallable(String name) {
        this.name = name;
    }

    @Override
    public String call() throws Exception
{ Thread.sleep(5000); return name; } }
public class ListenableFutureApp {

    public static void main(String[] args) {

         /*
          * 方法1:採用 ListenableFuture類自帶的addListener(Runnable listener, Executor executor)方法註冊回撥函式(不推薦)
          */
         ExecutorService executor = Executors.newFixedThreadPool(1
); ListeningExecutorService service = MoreExecutors.listeningDecorator(executor); MyCallable callable = new MyCallable("JayLai"); ListenableFuture<String> listenableFuture = service.submit(callable); final long time1 = System.currentTimeMillis(); //非同步方法 //註冊監聽,當Callable類者中call()方法執行結束,後會進入new Runnable() { }中 listenableFuture.addListener(new Runnable() { @Override public void run() { try { System.out.println("執行結果:" + listenableFuture.get()); long time2 = System.currentTimeMillis(); System.out.println("執行時間為:" + (time2 - time1) + "毫秒"); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }, executor); //註冊回撥函式 System.out.println("=======main method end======"); } }

執行結果:
這裡寫圖片描述

3 addCallback()方法

Guava包還提供了更加便利的註冊監聽方法,使用Futures類中的

public static <V> void addCallback(ListenableFuture<V> future,
      FutureCallback<? super V> callback) {
    addCallback(future, callback, directExecutor());
  }

註冊回撥方法,其中FutureCallback類的原始碼如下

public interface FutureCallback<V> {

  void onSuccess(@Nullable V result);

  void onFailure(Throwable t);
}

它具體2個方法,當Callable類成功執行結束時候,則進入onSuccess()方法中;若失敗,如遇到異常,則進入onFailure()方法。

public class ListenableFutureApp {
    public static void main(String[] args) {

        /*
         * 方法2:採用addCallback註冊回撥函式(推薦此法)
         */
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        MyCallable callable = new MyCallable("JayLai");
        Future<String> future = executorService.submit(callable);
        ListenableFuture<String> listenableFuture = JdkFutureAdapters.listenInPoolThread(future);
        long time1 = System.currentTimeMillis();
        //註冊回撥函式
        Futures.addCallback(listenableFuture, new FutureCallback<String>() {    //非同步執行
            @Override
            public void onSuccess(String result) {
                System.out.println("執行結果:" + result);
                long time2 = System.currentTimeMillis();
                System.out.println("執行時間為:" + (time2 - time1) + "毫秒");
            }
            @Override
            public void onFailure(Throwable t) {
                System.out.println("Error!!!");
            }
        });

        System.out.println("=====main method end !====");
    }
}

執行結果:
這裡寫圖片描述

4 參考文獻