2014-09-02 105 views

回答

3

那麼他們之一處理轉換Iterable例如和一個轉換(可能異步)從一個ListenableFuture到另一個。這些概念是完全不同的,並處理不同的事情。

這裏是一個AsyncFunction的小例子,基本上我們異步獲取一個String,然後將該String異步轉換爲一個不同的字符串。這只是一個示例,雖然..

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

     ExecutorService deletegate = Executors.newFixedThreadPool(1); 
     ExecutorService deletegateForAsyncFunction = Executors.newFixedThreadPool(1); 

     ListeningExecutorService pool = MoreExecutors.listeningDecorator(deletegate); 
     ListeningExecutorService poolForAsyncFunction = MoreExecutors.listeningDecorator(deletegateForAsyncFunction); 
     ListenableFuture<String> resultFromWorker = pool.submit(new Worker()); 

     ListenableFuture<String> finalResult = Futures.transform(resultFromWorker, new AsyncTransformation(poolForAsyncFunction)); 

     Futures.addCallback(finalResult, new MyFutureCallback()); 

    } 

    private static final class Worker implements Callable<String> { 
     public String call() throws Exception { 
      try { 
       System.out.println("Executing in thread="+Thread.currentThread().getName()); 
       //simultate some work 
       TimeUnit.SECONDS.sleep(3); 
      } catch(InterruptedException ex){ 
       ex.printStackTrace(); 
      } 
      return "CALCULATED_VALUE"; 
     } 
    } 

    /** 
    * Almost like Function transformation but it is asynchronous 
    */ 
    private static final class AsyncTransformation implements AsyncFunction<String, String> { 

     private final ListeningExecutorService poolToRunFunctionIn; 

     public AsyncTransformation(ListeningExecutorService poolToRunFunctionIn){ 
      this.poolToRunFunctionIn = poolToRunFunctionIn; 
     } 

     public ListenableFuture<String> apply(String input) throws Exception { 
      return poolToRunFunctionIn.submit(new FunctionWorker(input)); 
     } 

     /** 
     * 'worker' for the AsyncFunction 
     */ 
     private static final class FunctionWorker implements Callable<String> { 
      private final String input; 
      public FunctionWorker(String input){ 
       this.input = input; 
      } 
      public String call() throws Exception { 
       try { 
        System.out.println("Executing in thread="+Thread.currentThread().getName()); 
        TimeUnit.SECONDS.sleep(3); 
       } catch(InterruptedException ex){ 
        ex.printStackTrace(); 
       } 
       return input + "_TRANSFORMED"; 
      } 
     } 
    } 

    /** 
    * what do to when the ListenableFuture has been processed 
    */ 
    private static final class MyFutureCallback implements FutureCallback<String> { 
     public void onSuccess(String result) { 
      System.out.println("Result from computation = " + result); 
     } 

     public void onFailure(Throwable t) { 
      t.printStackTrace(); 
     } 
    } 
} 
+0

我懷疑這是如何工作。謝謝你確認我的懷疑。 – wlan0 2014-09-03 20:37:00

相關問題