I found the solution of my problem. The problem was in the configuration. We must specify that the Jersey servlet supports async
and then it works fine:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<async-supported>true</async-supported>
...
</servlet>
Please note that if you have Servlet filters, they also need to be async-supported
to true.
This was also not necessary to create a thread. Jersey does it for me:
@Path("/poll")
@GET
public void poll(@Suspended final AsyncResponse asyncResponse)
throws InterruptedException {
asyncResponse.setTimeout(30, TimeUnit.SECONDS);
this.asyncResponse = asyncResponse;
}
@POST
@Path("/printed")
public Response printCallback(String barcode) throws IOException {
// ...
this.asyncResponse.resume("MESSAGE");
return Response.ok().build();
}
When calling poll
the browser waits until receiving MESSAGE
or receiving a HTTP status 503 if the timeout is elapsed. In the server, the request thread is not blocked until the timeout but released directly. In the client side, I have a JavaScript which is calling the method again if the timeout occurs, otherwise I process something in the page.