Jersey Client, memory leak, static and concurrency

2.6k views Asked by At

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?

2

There are 2 answers

11
aioobe On BEST ANSWER

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);
    }

    ...
}
1
Filip On

As initially stated by Dejel, this is a known issue.

The "workarounds" work... but I believe this issue is critical and should be fixed by the Jersey team.

Let the Jersey team know that this affects YOU by logging in to JIRA and voting it up. It currently only has 3 votes :

https://java.net/jira/browse/JERSEY-2830