Narendra Verma
Narendra Verma

Reputation: 2422

Jersey-Client 1.2 - Jersey Client Performance Issue

I am using jersey-client-1.2 to access EHCache REST APIs to put/get my own custom objects.

Jersey Maven Dependency:

<dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-client</artifactId>
            <version>1.2</version>
</dependency>

Client Code:

MyObject myObject = new MyObject();
myObject.setName("Narendra");

long start = System.currentTimeMillis();
Client client = Client.create();            
WebResource webResource = client.resource("http://localhost:9080/ehcache-server/rest/mycache/");
System.out.println("Time spend in creating client - " + (System.currentTimeMillis() - start));

start = System.currentTimeMillis();
ClientResponse putResponse = webResource.type("application/x-java-serialized-object").put(ClientResponse.class, SerializationUtils.serialize(myObject));
System.out.println("Time spend in serializing and putting Object into cache - " + (System.currentTimeMillis() - start));

start = System.currentTimeMillis();   
ClientResponse getResponse =  webResource.accept("application/x-java-serialized-object").get(ClientResponse.class);
byte[] bytes = getResponse.getEntity(byte[].class);
System.out.println("Time spend in getting and deseralizing object from cache " + (System.currentTimeMillis() - start));

When I perform load test with above code, the application server (where above client is running) gives bad performance. Most of the threads went into waiting stage due to jersey client call.However, the server where cache REST APIs are deployed responding properly. It seems jersey client is not performing well.

Am I following best practices of Jersey client in above code? Am I missing anything which is causing performance issues? Any Idea please.

Upvotes: 2

Views: 4099

Answers (1)

Narendra Verma
Narendra Verma

Reputation: 2422

I got the solution. I was creating jersey client on each request. As per jersey 2.0 document, creation of client on each request is too costly.Below section is taken from same document:

Client instances are expensive resources. It is recommended a configured instance is reused for the creation of Web resources. The creation of Web resources, the building of requests and receiving of responses are guaranteed to be thread safe. Thus a Client instance and WebResource instances may be shared between multiple threads

As jersey client is thread safe, I created client at once and set it in singleton class as variable. Then created web resource from same client for different requests. So Client.create() must be called only once for multiple requests.

After testing application with load, it worked like charm and gave very good performance result. Performance improved by almost 95%.

Upvotes: 10

Related Questions