10

I'm using the Java 11 HttpClient with HTTP/2 and need to keep connection alive for few minutes, but the builder does not have the option to set it. Is there a way to specify this and make client keep the connection alive for some time?

Bobulous
  • 12,967
  • 4
  • 37
  • 68
qiGuar
  • 1,726
  • 1
  • 18
  • 34

2 Answers2

17

If you build a standard HttpClient e.g. using HttpClient.newHttpClient(); by default a connection pool is created. This pool keeps the connections alive by default for 1200 seconds (20 minutes).

If you want to change the keep-alive timeout you can do so using the property jdk.httpclient.keepalive.timeout. However the value is only read once when the class jdk.internal.net.http.ConnectionPool is loaded. Afterwards it can't be changed anymore.

Therefore you have to set this property for the whole JVM:

-Djdk.httpclient.keepalive.timeout=99999

Or at runtime before the ConnectionPool class has been loaded:

System.setProperty("jdk.httpclient.keepalive.timeout", "99999");

A third option is to using a file named ${java.home}/conf/net.properties and set the property in there.

Robert
  • 39,162
  • 17
  • 99
  • 152
  • Yes, this is what I need. Is there a way to configure the the pool size? Default timeout of 20 minutes is fine. – qiGuar Dec 05 '18 at 10:16
  • 2
    @qiGuar use the property `jdk.httpclient.connectionPoolSize` by default this property is `0` (unbound) – Robert Dec 05 '18 at 10:20
  • 2
    Let me try! So if it's unbound, it means that on every request it'll create new connection? Also, is there a documentation link for this info? thanks a lot for your answers! – qiGuar Dec 05 '18 at 10:41
  • 1
    Oh, the pool is used only for http 1.1, not for http 2 :( – qiGuar Dec 05 '18 at 11:00
  • @qiGuar Did you find the documentation for this property? – Shubham Oct 08 '20 at 11:31
  • 3
    @Shubham It is "documented" from source: https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.net.http/share/classes/jdk/internal/net/http/ConnectionPool.java#L54-L57 – Bill Lam Dec 28 '20 at 05:32
  • You can find these properties documented on oracle's site also: https://docs.oracle.com/en/java/javase/17/core/java-networking.html#GUID-82A738CB-2A1C-4AC8-B9DA-C4543D398B51 – Yonathan W'Gebriel Jan 13 '22 at 07:25
2

Both HTTP/2 and HTTP/1.1 connections are kept alive by default. There are some exceptions when several concurrent connections are opened to the same host - then only one of them will be kept alive.

daniel
  • 2,665
  • 1
  • 8
  • 18
  • 1
    how do you know that's the case? is this configurable, or documented somewhere? – liltitus27 Sep 19 '19 at 20:25
  • 1
    @liltitus27 From [the specification](https://tools.ietf.org/html/rfc7230#section-6.3): “If the received protocol is HTTP/1.1 (or later), the connection will persist after the current response…” [in the absence of a Connection: close header] – VGR Sep 24 '19 at 15:57