Search code examples
javaconcurrencyjerseyjersey-2.0jersey-client

Jersey Client, memory leak, static and concurrency


I am using Jersey Client (v2.17) to make external calls from my app.

I found out this memory leak bug (the CPU consumption was very high) which made me re-write my code to make the client static like this:

public class GeneralUtil {

    private static final Client client = ClientBuilder.newClient()


    public static String makeCall(String url) throws NotFoundException {
        return client.target(url).request().get(String.class);
      }
}

However, now I have concurrency problems - I am using this class to be called from multiple threads. I keep on getting:

org.apache.http.impl.execchain.RequestAbortedException: Request aborted

Any suggestion - how can I still prevent the memory leak, and still use the client?


Solution

  • If you don't want to create an arbitrary number of Client objects, you can use ThreadLocal and have one object per thread.

    You can override ThreadLocal.initialValue to return ClientBuilder.newClient() to automate creation of Client objects for new threads.

    Or you could make the methods synchronized, but that means that you will only be able to do one request at a time.

    Here's some example code:

    class GeneralUtil {
    
        ThreadLocal<Client> client = new ThreadLocal<Client>() {
            @Override
            public Client initialValue() {
                return ClientBuilder.newClient();
            }
        };
    
        public static String makeCall(String url) throws NotFoundException {
            return client.get().target(url).request().get(String.class);
        }
    
        ...
    }