By Jakub Podlesak-Oracle on Mar 30, 2015
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.
Tip 1: Be careful when updating WebTarget config!
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 documentation does not state this explicitly, so i will write it here in bold once more: be careful when touching configuration of a web target!. What does it mean? Whenever you create a new web target with updated configuration, Jersey will effectively create a new client runtime. To keep your application performing well, you should think of reusing all such web targets.
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.
Tip 2: Avoid WebTarget.register()
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.
Tip 3: Avoid WebTarget.property()
Tip 4: Use response.close() to release network connections!
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.