2012-04-25 134 views
2

我不明白AsyncResult類的想法。 從tutorial我瞭解到它的工作原理與FutureTask類一樣(但AsyncResult是可序列化的,所以它可以發送到本地或遠程客戶端)。 然而,doc說,此類方法不應該叫,所以我只能創建並返回這個類的一個實例:AsyncResult可以被認爲是可序列化的FutureTask嗎?

@Asynchronous 
public Future<String> processPayment(Order order) throws PaymentException { 
    ... 
    String status = ...; 
    return new AsyncResult<String>(status); 
} 

那麼什麼樣的對象將客戶端就取得?

我可以寫

@Asynchronous 
public AsyncResult<String> processPayment... 

在調用AsyncResult/Future的cancel(false)方法後容器是否會取消異步任務?

編輯: 我找到了答案thread

回答

0

您可以找到AsyncResult類文檔的理由:

注意,該對象未傳遞給客戶端。對於向容器提供結果值僅僅是一個方便。 因此,它的實例方法都不應該由 應用程序調用。

使用在第一個片段中定義的(正確)的簽名,客戶端將收到一個簡單的將來成爲:

@Singleton 
public class AsyncClient{ 
    @Inject PaymentProcessor proc; 
    public String invokePaymentProcessor(Order order){ 
     Future<String> result=proc.processPayment(order); 
     // should not block.... the container instantiates a Future and 
     // returns it immediately 
     return result.get(); // gets the string (blocks until received) 
    } 

} 

當然,如果容器還沒有開始的方法調用(即asyncronous調用仍然在processig隊列中),cancel(false)應取消調用(將其從隊列中移除),否則應在最終處理循環中指定cancel(true)並檢查SessionContext.wasCancelledPaymentProcessor.processPayment

相關問題