Using Keep-Alive to retain connection for duration

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • robertybob
    New Member
    • Feb 2013
    • 116

    Using Keep-Alive to retain connection for duration

    Hi.

    I am building an app that acquires data from a web service via HttpURLConnecti on. The app requests data every minute continuously whilst it is open and activated.

    At the moment I am opening and closing the connection each time it is required but is it better practise to have a single connection that persists?

    The current code is

    Code:
    URL url = new URL(tradeURL);
    connection = (HttpURLConnection)url.openConnection(Proxy.NO_PROXY);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder();
    String line;
    while((line = rd.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    rd.close();
    connection.disconnect();
    If it is better to re-use the connection from the initial request, how would I go about doing that?

    Also, is the keep-alive related to the domain level only - ie api.abcd.com - or is the entire url path involved?

    Many thanks!
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Use a connection pool!

    Your problem is not only that a connection is kept alive even if it is not used anymore, but also that the maximum number of connections is limited.
    This is all managed by a connection pool. (I have written my own connection pool many years ago, but now there are a lot of ready-made connection pools out for free usage. Just google for that.)
    Instead of opening and closing connections every time which is very costly, a connection pool will re-use existing connections.

    Comment

    • robertybob
      New Member
      • Feb 2013
      • 116

      #3
      Many thanks Chaarmann - I'm investigating this and will let you know.

      Comment

      • robertybob
        New Member
        • Feb 2013
        • 116

        #4
        Sorry - had to work on something else for a while and forgot all about this!

        For my needs I managed to get good enough stability using the generic keep-alive functionality and tweaks to the requests but Chaarmann's method seems to be decent solution for more complex requirements.

        Many thanks.

        Comment

        Working...