While fixing a memory leak issue in JerseyClient some time ago i realised how easy it is to misuse the thing.
In this blog post, i would like to introduce some tips to avoid unnecessary memory allocation and also to save some CPU cycles to achieve better throughput.
In Jersey 1.x it was suggested to reuse Client instances (see here for details).
In Jersey 2, reusing Client instances is still recommended, but as such it is not sufficient to keep things running efficiently. Application performance can easily be undermined here. Related documentation could be found in Jersey User Guide and the key sentence is quoted bellow:
The configuration principles used in JAX-RS client API apply to WebTarget as well.
The following picture depicts penalty that you could pay if you do not avoid the two main anti-patterns in this area. The graph captures total time required to make 50 thousand of HTTP get requests via Jersey client calls.
If you need to register some extra components, do it on the client already to prevent another client runtime creation. If you need another runtime, just try to register things once and reuse the resulting target instance.
When i wrote a simple test to get data for the above graph, i was getting short of available network ports. The problem is well described e.g. here. To avoid this i had to close responses. So as the last tip i recommend you close coming responses as well.