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.
The same applies to updating properties. These you can happily set on an Invocation or its builder
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.
THANK YOU FOR POSTING THIS !
I was trying to figure out why i was having new clients created every invocation. It looked related to my use of target.property(), but it wasn't clear what the alternatives were.
I couldn't find any of these explicit tips in the documentation, perhaps i missed it... but if they aren't there, i would think it would be of great benefit for others if they were included in performance related section.
Regarding response.close() - what if I use:
MyClassType res = target.request().get(MyClassType.class);
? will the response get closed?
Hi,
Not sure if you can post the source code for making the benchmark? I tried the same thing, but it seems like webtarget.register() and webtarget.property() doesn't make too much difference
Thanks