Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncHttpClient (Java) onComplete(): Does onCompleted() run on the separate thread?

Looking at the code block in the Java library AsyncHttpClient, the client starts a new thread (a Future) to make the request. Will the callback happen on the same thread, or will it run on the "main" thread (in this case, the thread where new AsyncHttpClient() was called?

import com.ning.http.client.*;
import java.util.concurrent.Future;

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
asyncHttpClient.prepareGet("http://www.ning.com/ ").execute(new AsyncCompletionHandler<Response>(){

    @Override
    public Response onCompleted(Response response) throws Exception{
        // Do something with the Response
        // ...
        return response;
    }

    @Override
    public void onThrowable(Throwable t){
        // Something wrong happened.
    }
});
like image 275
Roy Avatar asked Feb 18 '26 05:02

Roy


1 Answers

the client starts a new thread (a Future) to make the request.

Nope. The Future basically means: this method already returned but it didn't yet finished processing. The processing will continue in background (in some other thread you have no control over) and will finish some time in the future. You can ask this Future object to see whether the future already came or not (processing is done). You are not creating any thread yourself.

Think about ExecutorService. You are submitting some task to be done and waiting for a result. But instead of blocking, you get a Future which will give you back the result as soon as your submitted task reaches the thread pool and is processed.

Will the callback happen on the same thread, or will it run on the "main" thread

Neither. Your thread (the one that called AsyncHttpClient.execute()), by the time the response came back, is most likely doing something completely different. Maybe it serves another client or is already dead. You cannot just call arbitrary code on behalf of some thread.

In fact, this piece of code will be executed by internal NIO thread created by AsyncHttpClient library. You have absolutely no control over this thread. But you have to remember that this will happen asynchronously, so synchronization or some locking might be required if you access global objects.

like image 55
Tomasz Nurkiewicz Avatar answered Feb 20 '26 17:02

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!