users@jersey.java.net

Re: [Jersey] Proper way to structure code so that Client instances can be cleaned up

From: Paul Sandoz <Paul.Sandoz_at_Sun.COM>
Date: Wed, 23 Sep 2009 20:42:26 +0200

On Sep 16, 2009, at 9:05 AM, Gavin Bong wrote:

> Hi,
>
> Currently I am creating a WebResource inside a method like this:
>
>
> private WebResource resource( String user )
> {
> ClientConfig config = new DefaultClientConfig();
> Client client = Client.create(config);
> client.addFilter( new LoggingFilter() );
> WebResource resource = client.resource( _endpoint + "/" +
> user );
> return resource;
> }
>
>
> As you can see, I am not calling client.destroy(). Am I correct to say
> that I am probably leaking memory because of this ?
>

Not by default.

It means if you have any components included in the client
configuration that have pre-destroy method registered it will not get
called unless Client.destroy gets called.

You can use the @PreDestroy annotated method on a resource class to
destroy the client instance created by a resource.


> If multiple threads call my method, multiple instances of Client &
> WebResource will be created.
> When should I call Client.destroy() ? During servlet context
> shutdown ?
>

I recommend you create just one client instance as they are expensive
to create. As long as you do not configure the client after it starts
being used to obtain WebResource instances and make requests it is
thread safe.

We need to improve the use of the client side on the server side, so
that it is easy to obtain and re-obtain a Client instance, or
WebResource, appropriately configured so that you do not have to worry
about this aspect.

Paul.