2009-11-11 52 views
1

我有使用Axis2我稱之爲如下使用相同的回調Hanlder兩個不同的時間一個異步Web服務:asynchronus Web服務,回調問題

stub.startGetData("Foo",callbackhandler) 
stub.startGetData("bar",callbackhanlder) 

ServiceCallBackhandler callbackhandler = new ServiceCallBackhandler() { .....}; 
//ServiceCallBackhanlder and stub are generated from a WSDL file 

Synchronized(callbackhandler){ callbackhandler.wait()} 
//remaining code to be executed 
     ............ 
     ........... 

在這種情況下的問題是,「剩下的代碼」一旦呼叫在stub.startGetData("Foo",callbackhandler)後返回,就會被執行。我想要回調等待,直到它還處理完stub.startGetData("boo",callbackhandler)語句,然後執行剩餘的代碼。有沒有辦法做到這一點,而不使用兩個不同的callbackhanlders,因爲兩個返回值的處理是相同的。謝謝。

+0

你在使用什麼API - JAX-WS,JAX-RPC?你的存根如何產生。爲什麼你要等待異步響應,因爲Web服務是同步的? – Bozho 2009-11-11 19:30:39

回答

2

我想你想要這樣的東西...

import java.util.concurrent.CountDownLatch; 
... 

// set the latch count to the nuber of callbacks to wait for 
CountDownLatch latch = new CountDownLatch(2); 

ServiceCallBackhandler callbackhandler = new ServiceCallBackhandler() { 
     public void handleResponse(Response response) { 
      .... do real work ... 
      latch.countDown(); 
     } 
}; 

stub.startGetData("Foo",callbackhandler) 
stub.startGetData("bar",callbackhanlder) 

// wait for both callbacks to occur 
latch.await(); 

另請參見java.util.concurrent.Semaphore,但我認爲Cou ntDownLatch是你所描述的內容。

0

一般來說,如果想要等待某個特定條件適用於N個不同的對象,則應考慮使用來自併發實用程序的CyclicBarrier(N)或CountDownLatch(N)。

主叫體的基本結構:

CountDownLatch my_latch = new CountDownLatch(2); 

// These objects perform some asynchronous function when 
// their start() method is called. 
AsyncObject ao1 = new AsyncObject(my_latch, ...); 
AsyncObject ao2 = new AsyncObject(my_latch, ...); 

ao1.start(); // asynchronous, returns immediately 
ao2.start(); // asynchronous, returns immediately 

// my_latch.await() blocks until the latch has counted down to 0 from 2 
my_latch.await(); 

與來自希望「信號」的工作已經完成或條件滿足時,該方法中:

{ 
    // ... work ... 
    // work is complete 

    the_latch_passed_in_to_this_object.countDown(); 
} 
+0

Offtopic:cool gravatar! – BalusC 2009-11-12 13:09:05