20

Is it possible with OkHttpClient to limit the number of live connections? So if limit reached, no new connection is picked and established?

My app starts many connection at same time.

Abhishek Jain
  • 3,562
  • 2
  • 26
  • 44
János
  • 32,867
  • 38
  • 193
  • 353

2 Answers2

33

The number of connections is configurable in the Dispatcher, not in the ConnectionPool that only allows to configure the max idle connections and the keep alive functionality.

The dispatcher allows to configure the number of connections by hosts and the max number of connections, defaults are 5 per hosts and 64 in total. This can seems low for HTTP/1 but are OK if you use HTTP/2 as multiple requests can be send to one connection.

To configure the dispatcher, follow these steps :

Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(100);
dispatcher.setMaxRequestsPerHost(10);
OkHttpClient client = new OkHttpClient.Builder()
    .dispatcher(dispatcher)
    .build();
loicmathieu
  • 5,181
  • 26
  • 31
  • 2
    Isn't "request" different from "connection"? – object Jan 17 '20 at 13:15
  • I don't think setting a cap on maxRequests allows you to utilize http/2 concurrent streams over one connection. – szakal Feb 18 '20 at 22:32
  • I just made a small test, and looks like indeed "request" here is not the same as "connection". Limiting the number of requests here to 1 (for example), means that we'll lose the ability to multiplex requests over a single HTTP/2, as it will wait until each request finishes until it sends the next one. Looks like there is no way to limit the number of actual **connections**, but feel free to correct me. – rboy Apr 11 '20 at 15:31
  • the flow ensures that the Dispatcher actually "behaves like" a connection pool for you because it doesn"t let the system create new connections and calls if the threadpool is full. – newhouse Nov 02 '20 at 15:35
-2

You could attempt to configure the maximum number of idle network connections by setting a ConnectionPool on your OkHttpClient.Builder.

int maxConnections = 5;
int keepAliveDuration = 15000;
ConnectionPool cp = new ConnectionPool(maxConnections, keepAliveDuration, TimeUnit.MILLISECONDS);

new OkHttpClient.Builder()
    .connectionPool(cp)
    .build();
fractalwrench
  • 4,028
  • 7
  • 33
  • 49
  • 6
    first argument is maxIdleConnections. Only idleConnections will be cleared if keepAlive is expired. There is no way to block any requests if max live Connections are reached. – Muthukannan Kanniappan Jan 26 '18 at 10:55
  • This is not enough, this can limit the pool, OP asked for live call limitations, which can be achieved with the Dispatcher usage. – newhouse Nov 02 '20 at 15:34