5

I am using AsyncInvoker using Jersey 2.0. This works fine for me. However, thread is not ending after completion of the return. Please note that I don't expect any response for the services I call.

public Future<Response> fire(WebTarget webTarget) {
    Future<Response> response = null;

    try {
        response = webTarget.request(MediaType.APPLICATION_JSON_TYPE)
                             .accept(MediaType.APPLICATION_JSON_TYPE)
                             .headers(headers)
                             .async().get();
    }

    catch (Exception e) {  
        e.printStackTrace();
    } 

    return response;
}
Timo Salomäki
  • 7,099
  • 3
  • 25
  • 40
krutik
  • 119
  • 4

2 Answers2

0

As long as you don't do anything with the actual javax.ws.rs.core.Response that is provided to you once the future value resolves, the request response stream is kept open (and the thread associated with it the raw HTTP request as wel I guess). You should either:

  1. Do something with the javax.ws.rs.core.Response object and close it (or it's stream).
  2. Use .get(MyPojo.class) to have the response steam converted into an actual object. This will close the stream for you and resolve a MyPojo instance in the future instead.
0

You need to close your client object that you created in the calling method. In the calling method you would have something like below -

Client client = ClientBuilder.newClient();

WebTarget webTarget = client.target(SERVER_URL).path(API_PATH).path(String.valueOf(id));

fire(webTarget);

So you need to close your client after calling this method -

client.close()

However, the recommended way of closing client is after receiving response. Something like below -

public void fire(WebTarget webTarget) {

    try {
        webTarget.request(MediaType.APPLICATION_JSON_TYPE)
                             .accept(MediaType.APPLICATION_JSON_TYPE)
                             .headers(headers)
                             .async().get(new InvocationCallback<Response>() {

          @Override
          public void completed(Response response) {
              // Do whatever your wish with response
              client.close();
          }

          @Override
          public void failed(Throwable throwable) {
              throwable.printStackTrace();
              client.close();
          }
      });
    }
    catch (Exception e) {  
        e.printStackTrace();
    } 
}
Vikas Sachdeva
  • 5,633
  • 2
  • 17
  • 26