When Does RestAdapter establishes HttpConnection

HI,
I have the following piece of code :
RestClient.java :
package co.riva.vader;

import android.util.Log;

import com.google.gson.GsonBuilder;
import com.squareup.okhttp.OkHttpClient;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;
import retrofit.converter.GsonConverter;

public class RestClient<T> {
    private static final String LOGTAG = RestClient.class.getSimpleName();
    private static final int TIMEOUT_VALUE_IN_SECONDS = 10;

    private T _api;

    public RestClient(String endPoint, Class<T> apiClass, Executor callbackExecutor) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .setClient(new OkClient(okHttpClient)).setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade requestFacade) {
                    }
                }).setConverter(new GsonConverter(new GsonBuilder().create()))
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String s) {
                        Log.d(LOGTAG, s);
                    }
                }).setExecutors(Executors.newCachedThreadPool(), callbackExecutor).build();
        _api = restAdapter.create(apiClass);
    }

    public RestClient(String endPoint, Class<T> apiClass) {
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(TIMEOUT_VALUE_IN_SECONDS, TimeUnit.SECONDS);
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .setClient(new OkClient(okHttpClient)).setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade requestFacade) {
                    }
                }).setConverter(new GsonConverter(new GsonBuilder().create()))
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new RestAdapter.Log() {
                    @Override
                    public void log(String s) {
                        Log.d(LOGTAG, s);
                    }
                }).build();
        _api = restAdapter.create(apiClass);
    }

    public T getApi() {
        return _api;
    }
}

Open in new window


SuggestionClient.java :

package co.riva.vader;

import java.util.List;

import retrofit.http.GET;
import retrofit.http.Query;

public class SuggestionClient {
    private static final String ENDPOINT = "http://talk-to-kbb-614344748.us-west-1.elb.amazonaws.com";
    SuggestionApi _api;

    public SuggestionClient() {
        RestClient<SuggestionApi> restClient = new RestClient<>(ENDPOINT, SuggestionApi.class);
        _api = restClient.getApi();
    }

    public List<String> getSuggestions(String word, int count) {
        return _api.getSuggestions(word, count);
    }

    public interface SuggestionApi {
        @GET("/sug")
        List<String> getSuggestions(@Query("command") String word, @Query("nResults") int count);
    }
}

Open in new window


Now in my another class i create an object like :
    private SuggestionClient _suggestionClient = new SuggestionClient();
and then later make a call :
_suggestionClient.getSuggestions(constraint.toString(), 4);

My question is when does the HttpConnection gets established ? During the creation of the _suggestionClient variable or during the Call to getSuggestions()?
Here i have set the ConnectionTimeout for the httpClient to be 10seconds.
So once the connections gets established it will be reconnected only after 10 seconds ?
what happens if the connection is disconnected before 10seconds will it reconnect automatically ?
How to make the connection reestablish once the connection breaks down ?

thanks
Rohit BajajAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

mccarlIT Business Systems Analyst / Software DeveloperCommented:
My question is when does the HttpConnection gets established ? During the creation of the _suggestionClient variable or during the Call to getSuggestions()?
It would have to wait until the actual call to getSuggestions. In this simple case it is not obvious, but imagine if your api had multiple method calls, they can all have a different "path" specified in the @GET annotation. This "path" is part of the connection and so the connection can't be made until the path is known and this is only when the desired api method is called.

As for your other questions, it is easiest to imagine that each api call will make a separate connection to the web service get the data and then close the connection. Now that may not be entirely true, if the client may implement keep-alives and such at a low level, but for your understanding, just assume that it is one connection per one api call.

So what I assume the library developers would have intended by a "connection timeout" would be if the web service doesn't respond to the initial connection attempt (ie. if it is turned off or you have the wrong endpoint address, etc) then the client code will wait for 10 seconds before indicating an error, which I would assume it would do by throwing an exception.

If you want the code to attempt to re-establish the connection if the connection fails, you would do this in your own client code. You would put your call to the api method in a try-catch block and if the call throws an exception to can try to call the api method again and it may be successful the next time.
Rohit BajajAuthor Commented:
hi
doesnt the connection depends only on endpoint ?
does each separate request with differet get parameter need a separate http connection ?

what i want to achieve is that have the connection establishes beforehand and then call the api method so as to save time. is it possible to do so with above ?
mccarlIT Business Systems Analyst / Software DeveloperCommented:
doesnt the connection depends only on endpoint ?
The TCP socket connection depends only on part of the endpoint, but you have no visibility of this lower level stuff from your code, so you shouldn't worry about it.

does each separate request with differet get parameter need a separate http connection ?
Yes, however, as mentioned, this may use an already established TCP connection if it has been kept alive using keep-alives. Otherwise, it will just re-establish the TCP connection and then use that.

what i want to achieve is that have the connection establishes beforehand and then call the api method so as to save time
Is this an actual performance problem that you are encountering? If you haven't actually encountered any issues yet, you may be over thinking things (have a look at the following regarding "Premature Optimization" http://en.wikipedia.org/wiki/Program_optimization#When_to_optimize)

If you do have a performance issue, and having the connection established beforehand really does improve performance, the only way I can see is to just make a "dummy" call to the API at the point you want to establish the connection. Once this happens the TCP connection should be kept alive for the first real api call, whenever that may happen. But realise, that this is not foolproof. If something happens to that connection, it won't be re-established until the next api call, and hence you back to where you are now anyway. There is no way to detect that the TCP connection has been broken (at least not from your client code, anyway).



But I will say it again for maximum impact, please, please, please make sure you aren't wasting your time (and making bad code) by trying to fix a problem that isn't really there in the first place.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Rohit BajajAuthor Commented:
HI,
Thanks for that...
I am making the api call beforehand so as to maintain the conneciton (the server will typically maintain it for 5 minutes).  But i also need some way of detecting the disconnection so that i can reconnect it again.

How should i do that ?
As to why i need the connection established beforehand is because i came to know from my team mate that as our server is distantly located and it takes around 3 seconds for the conneciton to establish.
Thanks
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.