views:

253

answers:

2

I have a asynchronous web service using axis2 which I call two different times using the same CallBack Hanlder as follows :

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
      ............
      ...........

The problem in this case is that the "remaining code" is executed once the call returns back after the stub.startGetData("Foo",callbackhandler). I want the callback to wait until it has also finished processing the stub.startGetData("boo",callbackhandler) statement and then execute the remaining code. Is there a way to do it without using two different callbackhanlders, since the processing for both the return values is the same. Thanks.

A: 

Generally speaking, if one wants to wait until a specific condition holds for N number of different objects, they should consider using a CyclicBarrier(N) or CountDownLatch(N) from the concurrency utils.

Basic structure of the calling body:

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();

And from within the method that wishes to "signal" when its work is complete or the condition is met:

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

    the_latch_passed_in_to_this_object.countDown();
 }
charstar
Offtopic: cool gravatar!
BalusC
+1  A: 

I think you want something like this...

 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();

See also java.util.concurrent.Semaphore, but I think CountDownLatch is what you need from what you have described.

David Roussel