openstack4j icon indicating copy to clipboard operation
openstack4j copied to clipboard

Use same connection pool for all clients per OKHttp recommendations

Open sbrattla opened this issue 4 years ago • 0 comments

The OKHttp documentation recommends the following usage pattern:

The best practice in OkHttp 3 is to create a single OkHttpClient instance and share it throughout the application. Requests that needs a customized client should call OkHttpClient.newBuilder() on that shared instance. This allows customization without the drawbacks of separate connection pools.

The current HttpCommand implementation for OKHttp creates a new OkHttpClient for each request, and subsequently a new connection pool for each request. This may not be an big issue since the connection pool is set to allow 0 connections and also to evict connections after 500 ms. Nevertheless, the overhead of initializing a new connection pool and related threads for each and every http request may not be negligible for a large number of http requests.

This pull request attempts to address this by providing a singleton client available to all requests. This singleton client is not the client used for the actual http requests, but serves as a "template" client. We use client.newBuilder() to create a shallow copy of the singleton client. This will reuse the existing connection pool, but still enable us to fully customize each http request.

The singleton OkHttpClient will be instantiated in the initialize method of HttpCommand.

sbrattla avatar Oct 14 '19 12:10 sbrattla