简体   繁体   中英

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?

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

    ...
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM