Search code examples
jax-rsresteasyjersey-client

JAX-RS Client API async request


I am trying to use the JAX-RS Client API to request a resource through HTTP GET, by using the following code: (I used jersey-client v2.12 and also resteasy-client v3.0.8.Final to test the implementation)

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;

public class StackOverflowExample {
  public static void main(String[] args) {
    Client client = ClientBuilder.newClient();
    client.target("http://example.com/").request().async().get(new InvocationCallback<String>() {
      @Override
      public void completed(String s) {
        System.out.println("Async got: " + s);
      }

      @Override
      public void failed(Throwable throwable) {
        System.out.println("Async failure...");
      }
    });
  }
}

As I expected the String is printed almost immediately. But the process keeps running about one minute, although there isn't any code that should be executed.

The JAX-RS spec just says that we should use the InvocationCallback and nothing else that matters to my issue. But even if I use a Future the same effect happens. I also tested, if this has something to do with a timeout, which was very unlikely and wrong. The debugger shows that there are some threads running namely DestroyJavaVM and jersey-client-async-executor-0 or pool-1-thread-1 in the case of resteasy.

Do you have any idea what is going wrong here?


Solution

  • It is allways helpful to consult the JavaDoc. Concerning my issue it says:

    Clients are heavy-weight objects that manage the client-side communication infrastructure. Initialization as well as disposal of a Client instance may be a rather expensive operation. It is therefore advised to construct only a small number of Client instances in the application. Client instances must be properly closed before being disposed to avoid leaking resources.

    If I close the client properly everything is working as expected.

    public class StackOverflowExample {
      public static void main(String[] args) {
        Client client = ClientBuilder.newClient();
        // request here
        client.close();
      }
    }