Search code examples
javaasynchronouscallbackfuturetask

Implementing asynchronous call using FutureTask and callback


So right now, I am trying to implement an asynchronous call which calls my BasicHttpClient to get Http response from the internet, when the Http client done its work, it calls one of Callee class's methods.

Generally, my implementation looks like this.

public class BasicHttpClientAsync {
    private OnRequestFinishedListener mListener;

    public interface OnRequestFinishedListener {
        public void onRequestFinished(HttpResponse httpResponse);

        public void onRequestFinished(ClientProtocolException e);

        public void onRequestFinished(IOException e);
    }

    public BasicHttpClient(OnRequestFinishedListener listener) {
        this.mListener = listener;
    }

    private Runnable task = new Runnable() {
        @override
        public void run() {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(URL);
            HttpResponse httpResponse = httpClient.execute(httpGet);

            mListener.onRequestFinished(httpResponse);
        }
    };

    public void getResponse() {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        FuturkTask<?> futureTask = new FutureTask<Object>(task, null);
        executor.execute(futureTask);
    }
}

public class Callee implements OnRequestFinishedListener {
    public void getResult() {
        BasicHttpClientAsync httpClient = new BasicHttpClientAsync(this);
        httpClient.getResponse();
    }

    @override
    public void onRequestFinished(HttpResponse httpResponse) {
        System.out.println(httpResponse.toString());
    }
}

The code has been largely simplified, and main() method calls Callee class's getResult() method. btw all of the exceptions has been handled, and send back to callee using callback.

However, the "onRequestFinished" in the Callee class seems like never get called.

Help please.


Solution

  • Turns out it's because I didn't add all of jars of apache's HttpComponents into my Java Build Path, which causing HttpClient mHttpClient = new DefaultHttpClient() throws out an exception. However, I am using Runnable, so there is no way for me to catch that exception.