rollinwiththepunches
rollinwiththepunches

Reputation: 21

java analog to the C# APM / IHttpAsyncHandler

I have implemented asynchronous http request processing in C# with the .Net asynchronous programming model, via IHttpAsyncHandler.

I'm new to java, but want to accomplish the same end -- begin a request, have it surrender the request-handling-threadpool thread and process asynchronously, signal when all processing is completed, triggering the handler's end request callback and writing the processing result to the response stream.

I feel sure this must exist, and I don't need to roll my own solution, but searching for async http handling turns up only AJAX-centric solutions (I want async processing on the server side).

Is there an analog to IHttpAsyncHandler in java?

Upvotes: 2

Views: 341

Answers (2)

toohool
toohool

Reputation: 1147

Java Servlet 3.0 adds asynchronous support analagous to that of ASP.NET.

http://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3

Support is available in newer versions of servlet containers such as Tomcat 7.0.

Upvotes: 1

Peter Knego
Peter Knego

Reputation: 80340

In Java Servlets every request gets it's own thread and does not limit processing of other requests. So, in principle they are already asynchronous: http://www.codestyle.org/java/servlets/faq-Threads.shtml

AFAIK, IHttpAsyncHandler in .Net is supposed to be higer-performance, but not everybody agrees: http://geekswithblogs.net/SanjayU/archive/2009/01/06/ihttphandler-vs-ihttpasynchandler.aspx

Update:

To start multiple parallel tasks and wait for all of them to finish, it's best to use ExecutorService. You could do something like this inside your Servlet method:

    ExecutorService executor = Executors.newCachedThreadPool(numThreads);
    for (int i = 0; i < numParallelTasks; i++) {
        Runnable worker = new MyRunnable();
        executor.execute(worker);
    }
    // This will make the executor accept no new threads
    // and finish all existing threads in the queue
    executor.shutdown();
    // Wait until all threads are finish
    while (!executor.isTerminated()) {

    }
    // all tasks done

Upvotes: 0

Related Questions