Skip to content

Instantly share code, notes, and snippets.

@games647
Last active March 7, 2020 20:56
Show Gist options
  • Save games647/924ae035ab3586e6bbee2894b4b64cd5 to your computer and use it in GitHub Desktop.
Save games647/924ae035ab3586e6bbee2894b4b64cd5 to your computer and use it in GitHub Desktop.
Java HTTP Keep-Alive Summary
* HTTP Keep alives are enabled by default and hold a connection up to a couple of minutes.
* By default up to 5 connections per destination are hold up
* You can disable it by calling explicitly disconnect
(Note: For android you should call disconnect always)
* For re-use the following has to be true
* share similar settings like same **instance** of SSLFactory
* Server has to accept keep-alive (no close)
* Fully consume inputstream, outputstream and errorstream and close it
(Since JDK 6: spawns a extra thread that consume some remaining data if the length is longer it's not used for keep-alives)
With a Debugger you can see it this example will spawn a Keep-Alive thread:
try (OutputStream out = con.getOutputStream()) {
// write
} catch (IOException ioEx) {
//handle
}
// if no errrors
try {
try (InputStream in = con.getInputStream()) {
// have to be inside, because it calls getInputStream too
con.getResponse()
// read fully
System.out.println(in.getClass());
} catch (IOException ioEx) {
ioEx.printStackTrace();
try (InputStream errStream = con.getErrorStream()) {
if (errStream != null)
// read fully
errStream.skip(Integer.MAX_VALUE);
} catch (IOException errIoEx) {
// re-throw only original exception
}
throw ioEx;
}
} catch (IOException ioEx) {
//
}
Sources:
* Java Source-Code: KeepAliveCleaner
* https://stackoverflow.com/questions/9943351/httpsurlconnection-and-keep-alive
* https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html
* https://en.wikipedia.org/wiki/Keepalive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment