Design pattern to handle an asynchronous response in Java

Raymond Chenon picture Raymond Chenon · Aug 3, 2011 · Viewed 24.5k times · Source

I read answers from similar Q&A

How do you create an asynchronous HTTP request in JAVA? | Asynchronous programming design pattern |
AsyncTask Android - Design Pattern and Return Values

I see a lot of solutions , but none really satifies me.

Listener way

Once the results are caught, the processing is implemented in onResult method.

public interface GeolocationListener {
public void onResult(Address[] addresses);
public void onError(Exception e);
}

This solution doesn't quite satify me , because I want to handle the results in the main method. I hate this interface because when the response is returned, it is processed in onResult resulting in chains of processing and no way to go back to the "main" method.

The servlet way

public class SignGuestbookServlet extends HttpServlet {

    public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
        // ...
        resp.sendRedirect("/guestbook.jsp");
    }
}

There is no exposed Java code calling the servlet. All the configuration is done in the web.xml

The way I want

Wait for the response like this

Response a = getResponse();
// wait until the response is received, do not go further
// process
Response b = getResponse();
// wait until the response is received, do not go further
process(a,b);

Is there a design pattern to handle the async request and wait for the response like above ? Other way than the listener. Please no library or framework.

EDIT Thanks so far the responses. I didn't give you the full picture so I exposed the Geolocation class I started the implementation . I don't know how to implement the method . Can someone shows "how to" ? He (or she) must also implement the listener to retrieve the results

private Address getFullAddress (String text, AddressListener listener, ... ){

    // new Geolocation(text, listener, options).start() 
    // implements Geolocation.GeolocationListener   
    // how to return the Address from the onResult ?
}

Answer

toto2 picture toto2 · Aug 3, 2011

First, you should not reject the first two methods you discuss. There are very good reasons people are using those techniques and you should try to learn them instead of creating new ones.

Otherwise, you should look at java.util.concurrent:

ExecutorService es = Executors.newFixedThreadPool(2);
...
Future<Response> responseA = es.submit(responseGetter);
Future<Response> responseB = es.submit(responseGetter);

process(responseA.get(), responseB.get());

where responseGetter is of type Callable<Response> (you must implement the method public Response call()).