Question

I have a requirement where, as part of a Web Service [ Java ], I enter details of a job into Database, which is asynchronously processed by a Windows Service [ C# ] and makes a HTTP Restful call to the Java web service notifying the status of the job.

The scenario:

  • Client makes a synchronous Restful call to the Java Web Service.
  • The Java Web Service enters the job details into database (similar to making an asynchronous call) and waits for a response back from the Windows Service (which is a new HTTP request to the Java Web Service).
  • Based on the response received, the Java Web Service needs to respond back to the client who is waiting on the synchronous call.

How can we achieve this in the Java Web Service?

EDIT: I've implemented restful web-service using Jersey framework and is running on a Jetty Server.

Was it helpful?

Solution

Depending on which versions of Jersey and Jetty you are using, you may be able to use the support for asynchronously handling requests added in Servlet 3.0. (Based on the Jetty Wikipedia page, I believe you need at least Jetty 8.x. Based on this article, I believe you need at least Jersey/JAX-RS 2.0.)

The Jersey documentation and the JAX-RS API docs have examples of how to asynchronously (i.e. in another thread) complete an outstanding request:

@Path("/resource")
public class AsyncResource {
    @GET
    public void asyncGet(@Suspended final AsyncResponse asyncResponse) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = veryExpensiveOperation();
                asyncResponse.resume(result);
            }

            private String veryExpensiveOperation() {
                // ... very expensive operation
            }
        }).start();
    }
}

In your case you would store the AsyncResponse object in such a way that, once you have received the response from the other web service, you complete the request by calling resume with whatever response you want to send to the client.

See also:

What is the purpose of asynchronous JAX-RS

JAX-RS and Long Polling

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top