0

I have method in class MyClassB which is triggered asynchronously from a method of MyClassA:

public void getProductCall()
{
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                productRequest = service.createS4ProductRequest(getRepriceItems());

//Below is a rest call to another system String response = pricing.getS4ProductResponse(quote.getAssetQuoteNrAndVrsn(), productRequest); //I'm using the below 2 lines to check from ClassA's method to see if this process has ended setProductResponse(response); productPriceProcessEnded=true;

            } catch (Exception e) {
                productPriceErrorOccured=true;
                e.printStackTrace();

            }
        }
    }).start();
}

This is the piece of code in MyClassA i used to check if the above method is complete.

for(int i=0;i<1000000000;i++)
{
    if(!networkAsynCalls.isListPriceErrorOccured())
{
    if(networkAsynCalls.isListPriceprocessEnded())
    {
        return networkAsynCalls.getListReponse();   
    }
    else
    {
        Thread.sleep(250);
        continue;
    }

}
else
    return null;
}

instead of using this random for loop can i use some inbuilt method or service pool or something ? Because,

1) This thread on method is in another class 2) In class MyClassB i have few more methods like this, so i need to check the status of all the methods in MyClassA

Thanks for any help.

arun
  • 1
  • 4

1 Answers1

0

If I undestand what you're trying to do is dispatch some code to be ran asynchronously, then be able to wait until it is completed (successfully or failed). If that's the case, you should take a look at Futures.

Here is an example based on the Javadoc:

FutureTask<String> future =
   new FutureTask<String>(new Callable<String>() {
     public String call() {
       // do stuff
       return "result";
   }});

This code creates an object "future" that can be invoked to execute searcher.search(target). At this point, the code is not executed at all. You simply have an object representing a computation that may be executed asynchronously. To do so, you'd call:

 ExecutorService executor = Executors.newFixedThreadPool(5);
 executor.execute(future);

This snippet created an Executor (which is a fixed pool of 5 threads), then handed over the future to it for execution. The executor will run the computation from Future asynchronously.

Future offers some methods (see the Javadoc) to wait until completion, cancel, check completion status, etc. For example,

 String result = future.get();

will block, waiting for the result indefinitely. A get(10, TimeUnit.SECONDS) will wait for 10 seconds and if the future has not completed, throw.

Galo Navarro
  • 440
  • 2
  • 9