Monday May 31, 2010

TOTD #139: Asynchronous Request Processing using Servlets 3.0 and Java EE 6

Server resources are always valuable and should be used conservatively. Consider a Servlet that has to wait for a JDBC connection to be available from the pool, receiving a JMS message or reading a resource from the file system. Waiting for a "long running" process to completely blocks the thread - waiting, sitting and doing nothing - not an optimal usage of your server resources. Servlets 3.0 introduces the ability to asynchronously process requests such that the control (or thread) is returned back to the container to perform other tasks while waiting for the long running process to complete. The request processing continues in the same thread after after the response from the long running process is returned or or may be dispatched to a new resource from within the long running process. A typical use case for long running process is a Chat Application.

The asynchronous behavior need to be explicitly enabled on a Servlet. This is achieved by adding "asyncSupported" attribute on @WebServlet as shown below:

@WebServlet(name="AsyncServlet", urlPatterns={"/AsyncServlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {

The asynchronous processing can then be started in a separate thread using "startAsync" method on the request. This method returns "AsyncContext" which represents the execution context of the asynchronous request. The asynchronous request can then be completed by calling AsyncContext.complete (explicit) or dispatching to another resource (implicit). The container completes the invocation of asynchronous request in the later case.

Lets say the long running process is implemented as:

class MyAsyncService implements Runnable {
    AsyncContext ac;

    public MyAsyncService(AsyncContext ac) { = ac;

    public void run() {
        System.out.println("Some long running process in \\"MyAsyncService\\"");

Note this is running in a separate thread. This service can be invoked from the original servlet as:
AsycnContext ac = request.startAsync();

The service may also be started as:

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.execute(new MyAsyncService(ac));

The ScheduledThreadPoolExecutor usage is recommended as it makes the thread management easier.

A listener can be associated with the AsyncContext to get notified of when the async request is complete, timed out, or resulted in an error. This can be achieved as:

ac.addListener(new AsyncListener() {

    public void onComplete(AsyncEvent event) throws IOException {

    . . .

A more complete code for the above fragment is given below. The "onComplete" method is used to clean up resources created during async processing.

The asynchronous request processing can be either completed in "run" method of "MyAsyncService" by invoking "AsycnContext.complete" as shown below:

public void run() {
    System.out.println("Some long running process in \\"MyAsyncService\\"");

or dispatched to a different resource as:

public void run() {
    System.out.println("Some long running process in \\"MyAsyncService\\"");

Lets take a look at our complete code:

@WebServlet(name="AsyncServlet", urlPatterns={"/AsyncServlet"}, asyncSupported=true)
public class AsyncServlet extends HttpServlet {
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            System.out.println("Starting doGet");
            AsyncContext ac = request.startAsync();
            ac.addListener(new AsyncListener() {

                public void onComplete(AsyncEvent event) throws IOException {

                public void onTimeout(AsyncEvent event) throws IOException {

                public void onError(AsyncEvent event) throws IOException {

                public void onStartAsync(AsyncEvent event) throws IOException {

            System.out.println("Do some stuff in doGet ...");

            // Start another service
            ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
            executor.execute(new MyAsyncService(ac));

            System.out.println("Some more stuff in doGet ...");
        } finally { 

    class MyAsyncService implements Runnable {
        AsyncContext ac;

        public MyAsyncService(AsyncContext ac) {
   = ac;
            System.out.println("Dispatched to " + "\\"MyAsyncService\\"");

        public void run() {
            System.out.println("Some long running process in \\"MyAsyncService\\"");

Invoking the GET operation of this Servlet shows the following sequence of statements in GlassFish server log:

INFO: Starting doGet
INFO: Dispatched to "MyAsyncService"
INFO: Doing some stuff in doGet ...
INFO: Some more in doGet ...
INFO: Some long running process in "MyAsyncService"
INFO: onComplete

The first statement marks the beginning of "doGet", the second statement indicates that the request is dispatched to the long running
"MyAsyncService", the third and fourth statement indicates that the response returned back to "doGet" for normal request processing. Finally fifth and sixth statement shows that now the asynchronous request is getting processed and is completed.

Clean and simple!

A request may be dispatched from Asynchronous servlet to Synchronous but other way around is illegal. The section in the Servlets 3.0 specification provides an introduction to the Asynchronous Processing in Servlets 3.0.

The asynchronous behavior is available in the Servlet Filter as well.

The complete code used in this blog can be downloaded here. A fully working sample of a Chat Application using Servlets 3.0 can be seen here.

Technorati: totd glassfish v3 servlets javaee asynchronous comet

Tuesday Oct 21, 2008

Comet @ Ajax World 2008 West

Jim and I presented on "Using Comet to create a Two-Player Web Game" at Ajax World 2008 West yesterday. The talk explained the basic concepts of Comet, showed how a Tic Tac Toe game can be easily created using code walkthrough and then talked about future directions. The slides are available here and the code can be downloaded here.

A similar sample that can be deployed on Rails and Grails is described here. It uses GlassFish's support for multiple dynamic languages and associated web frameworks.

One of the benefits of delivering first talk in the morning is the ability to attend different sessions during the day. Of the different sessions I particularly enjoyed listening Bill Scott on Crafting Rich Web Interfaces.The talk explained six principles of rich web interaction with set of design patterns and real world examples. The slides are available here. All other sessions were mostly product pitches with very little value for developers.

Here are some pictures from the show:

And a complete album is available at:

Technorati: conf ajaxworld comet glassfish

Wednesday Oct 15, 2008

"Using Comet to Create a Two-Player Web Game" @ Ajax World

Jim and I are speaking at Ajax World next week on Using Comet to Create a Two-Player Web Game.

The session walks through the process of creating a Tic Tac Toe game that can be played over the Internet using Ajax and Comet. In the process, it explains the general Comet concepts using APIs specific to the GlassFish Application Server. It also highlights the multi-lingual capabilities of GlassFish v3 by deploying a similar application using Ruby-on-Rails.

Here is the list of other Sun sessions:
The complete schedule shows a list of all the sesssions.

Technorati: conf ajaxworld comet glassfish

Sunday Mar 16, 2008

Ajax World New York 2008 - This Week

Sun Microsystems is a Gold sponsor of Ajax World East 2008. The event kick starts in New York City tomorrow and you can see the complete agenda here.

From Sun speakers, you'll hear how jMaki, GlassFish Comet, GlassFish and NetBeans provide an easy-to-use and industry-grade platform to develop and deploy Rich Internet Applications. Here is the list of Sun sessions:

Here is my wish list of sessions that I'd like to attend:

Tuesday, Mar 18
Picking the Right Technology for Rich Internet Applications Track 5 2:00 - 2:45pm
Ajax Applicability: When should Ajax be used ? Track 2 2:50 - 3:35pm
RIA Approach for Web 2.0 Development using jMaki Track 3 3:40 - 4:25pm
Wednesday, Mar 19
Opening Keynote: Can we fix the Web ? Opening Keynote 7:30 - 8:20am
Think Fast: Accelerate Ajax Development with Appcelerator Session 2 8:25 - 9:15am
REST and Ajax Reconciled Track 6 9:20 - 10:05am
Enterprise Comet: Real-Time or Real-Time Web 2.0 ? Session 4 11:00 - 11:30am
jMaki as an Ajax Mashup Framework Session 5 11:35 - 12:05pm
Understanding the top Web 2.0 Attack Vectors Track 3 12:10 - 12:55pm
Building Web 2.0 Applications with Project Zero Track 3 2:05 - 2:50pm
Ajax and Social Computing for the Enterprise Session 7 2:55 - 3:30pm
Aptana IDE: Your unfair advantage for Ajax etc. Track 3 5:20 - 6:05pm
SYS-CON.TV Power Panel: The Business Value of RIAs Session 10 6:10 - 6:55pm
Welcome Reception 6:30 - 8:30pm
Thursday Mar 20
RIA Adoption in 2008: Risks, Rewards, Challenges & Opportunity Opening Keynote 8:00 - 8:50am
Ajax and Rails Track 6 8:55 - 9:40am
Now Playing: Desktop Apps in the Browser Session 3 9:45 - 10:15am
DreamFace: The Ultimate Framework for Creating Personalized Web 2.0 Mashups Session 4 11:55 - 12:25pm
Securing Ajax Development and Testing Track 6 12:30 - 1:15pm
Asynchronous Ajax for Revlutionary Web Applications Track 3 2:15 - 3:00pm
Saving your Investment: Transforming J2EE Applications into Web 2.0 using GWT Track 4 3:05 - 3:50pm
Building Scalable Ajax Applications using GlassFish Comet Track 4 5:30 - 6:15pm
SYS-CON.TV Power Panel: What Lies Beyond AJAX? Session 9 6:15 - 7:00pm

It's only a wish list cause I'll be spending time at Sun booth in the Expo Floor as well and this is New York City ;)

See ya there!

Technorati: conf sun ajaxworld jmaki glassfish mashups comet netbeans ria

Tuesday Mar 20, 2007

Day 2 at Ajax World

After spending the evening at Times Square yesterday, I rolled early in the bed to attend the morning keynote at 7:30am. And I had to run before that :) So I attended three sessions before the Expo Floor opened.

Like yesterday, the opening keynote, scheduled for 7:30am, started at 7:45am. I've a 10am flight tomorrow morning so with this consistent delayed start, I might have to miss the keynote tomorrow although I'd very much like to attend it.

Jeremy said even though folks have been using Ajax-like technologies for years but without Google Maps and GMail, we wouldn't be in this room, not so many and not so fired up. There were approximately 300 people for this 7:30am session. This is nothing compared to JavaOne keynote which typically has between 8000 to 12000 people in the keynote but the overall attendance of this conference itself is around 800. So in terms of percentage, it's still decent.

The opening keynote was by Bret Taylor who founded and led Google Maps. He showed 5 lines of code to integrate Google Maps in a website and another 8 lines of code to integrate Google Search. The point was that it is really easy to work with Ajax, especially as compared with SOAP/WSDL stack. Then he explained some of the techniques used behind Google Maps and GMail to solve some of the common problems of Ajax.

Per him, the main reason that triggered the explosive growth of Ajax is that most of the major browsers (IE, Firefox, Safari, Opera) agreed to deal with DOM, XHR, hash/anchor encoding and such similar techniques that enable Ajax in a consistent manner. He then explained how technology/browsers are evolving, on a daily basis, to make it a more pleasant experience.

The second session was "Inside the U.S. Air Force: How AJAX Is Improving Communications and Quality of Life" - a joint talk by Tony Tran & Peggy Rackstraw. Tony Tran, Vice President of Roundarch who build the employee portal for Air Force explained how Air Force is adopting Ajax/RIA. Tony showed samples, using before and after comparison of clicks and page refreshes, of how adding RIA to the Air Force portal increased productivity of the employees by making the website easier to use. After a good success in their first phase, they worked with Laszlo systems to solve their distributed email system (higher TCO, multiple email servers/domains, basic editing capabilities) and IM within the team and friends & families. Then Peggy from Laszlo Systems demoed "Deployed Life" which had initial problems with Firefox but then worked with IE. IM was cool because it allowed a drag-and-drop of pictures/videos from your local machine.

The third session was "Enterprise Ajax Using Java" by Greg Murray. The talk was about newly launched Sun Web Developer Pack and how jMaki provides an extensible framework to develop your Ajax applications. The talk was full of demos making it more real. I talk about SWDP and jMaki on my blog anyway, so won't dwell in details here. And now I'm sitting at Sun pod.

At Sun pod, we are showing jMaki Charting, Theming, Glue, Mashups along with other cool features, Grizzly Comet demo, Phobos CRUD generator, RESTful Web services API and lots of other stuff. All of these technologies are available in recently released Sun Web Developer Pack that can be run on top of GlassFish v2. Come by and talk to us.


Tonight is Ajax on Hudson and I'm looking forward to that.

Technorati: ajaxworld sun swdp glassfish grizzly comet jmaki web2.0

Monday Mar 19, 2007

Day 1 - Reporting from Ajax World

I arrived in New York City yesterday early morning to show Sun's offerings at Ajax World. The Roosevelt Hotel reservation desk was courteous to allow me a really early check in (7am). After spending day with family & friends yesterday, I attended the opening keynote by Douglas Crockford this morning. After 20 minutes of delay Jeremy Geelan of SYS-CON, chair of the show, opened it and highlighted that they are neither vendors nor developers and they are here to listen and share with the community. I think that was an interesting statement considering there are multiple players involved in the game.

Doug started with a show of hands asking questions about Ajax awareness and finally asked "Who knows what does Web 2.0 mean?". And there were around approx 10 hands showed up. This term "Web 2.0" is fuzzy and any attempt to version the world wide web seems irrational. At Sun, we refer to this fuzzy term as "Next Generation Web Application" that allow to develop Rich Internet Applications. But you'll see Sun using "Web 2.0" sometimes because of a general adoption of this term.

Sun Web Developer Pack is one such toolkit that provides binaries, tutorial, documentation, samples (including source) to build your next generation Web applications and deploy them on industry-grade containers such as GlassFish and Sun Java System Web Server and others.

Most of Doug's slides were saying just few words and then he was talking through them. He introduced Ajax, it's history, different attempts at Rich Internet Application development, JavaScript, security in Ajax applications, Ajax in mobile applications, and competition (Adobe's Apollo and Microsoft's WPF).

Even though the keynote started late, but it finished slightly before time allowing me to attend Real World Web 2.0 Comet-based Applications by Jean Francois. There he gave an overview of the problem solved by Comet, different approaches of Comet, Grizzly Comet in GlassFish, and how to write a Comet application using GlassFish. In summary, Grizzly Comet solves reduce the latency and load on server but there is no standard way to for Comet-based applications so there is no interoperability between implementations. Please stop by at Sun's booth if you are interested in seeing a demo or talk more about Sun's offerings in this space.

A complete glimpse of schedule is available here and Sun sessions are listed here.

As a side note, I find it weird that there is no free internet connectivity at Ajax World. Isn't the conference about sharing, community and connectivity ?

Technorati: ajaxworld sun swdp glassfish grizzly comet


profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.

Java EE 7 Samples

Stay Connected


« July 2016