It's not clear must I close JAX RS Client/Response instances or not. And if I must, always or not?
According to documentation about the Client class:
Calling this method effectively invalidates all resource targets produced by the client instance.
The WebTarget class does not have any invalidate()/close() method, but the Response class does. According to documentation:
Close the underlying message entity input stream (if available and open) as well as releases any other resources associated with the response (e.g. buffered message entity data).
... The close() method should be invoked on all instances that contain an un-consumed entity input stream to ensure the resources associated with the instance are properly cleaned-up and prevent potential memory leaks. This is typical for client-side scenarios where application layer code processes only the response headers and ignores the response entity.
The last paragraph is not clear to me. What does "un-consumed entity input stream" mean? If I get an InputSteam or a String from response, should I close the response explicitly?
We can get a response result without getting access to Response instance:
Client client = ...;
WebTarget webTarget = ...;
Invocation.Builder builder = webTarget.request(MediaType.APPLICATION_JSON_TYPE);
Invocation invocation = builder.buildGet();
InputStream reso = invocation.invoke(InputStream.class);
I'm working with RESTeasy implementation, and I expected that response will be closed inside of resteasy implementation, but I could not find it. Could anyone tell me why? I know that the Response class will implement Closeable interface But even know, the Response is used, without closing it.
According to the documentation
close()
is idempotent.So you can safely close the
InputStream
yourself and should.That being said I style wise would not do
invocation.invoke(InputStream.class)
as theinvoker(Class)
is made for doing entity transformation. Instead if you want InputStream you should probably just callinvocation.invoke()
and deal with theResponse
object directly as you may want some header info before reading the stream. The reason you want headers when dealing with a responseInputStream
is typical because you either don't care about the body or the body requires special processing and size considerations which is what the documentation is alluding to (e.g.HEAD
request to ping server).See also link
So if you choose anything other than
InputStream
you will not have to close theResponse
(but regardless its safe to do it anyways as its idempotent).Looking into the
resteasy-client
source code,Invocation#invoke(Class<T>)
is simply callingInvocation#invoke()
and callingInvocation#extractResult(GenericType<T> responseType, Response response, Annotation[] annotations)
to extract the result from theResponse
:Invocation#extractResult(GenericType<T> responseType, Response response, Annotation[] annotations)
closes the Response in thefinally
block: