• No replies
8 Posts

Pinned topic Asynchronous Servlet

‏2013-09-05T15:47:07Z |


I am looking at how best to perform Comet style interaction using Servlet 3.0 and Asynchronous Servlets; and have been reviewing the example chat application that comes as part of the JEE6 SDK provided by Oracle.

One thing I am considering is how to manage a thread of execution that has access to the AsyncContext?

The Oracle example starts a new thread from within the servlet init method, by using an anonymous runnable class and executes this using a new Thread.  Does this not break the JEE spec? i.e. JEE Applications should not start and manage their own threads?  As new requests arrive, Async.start() is called and the resulting AsyncContext is saved in a static variable in the servlet.   The previously created thread then runs against the saved AsyncContexts sending new information as and when required.

How else could this be done?  I see that the AsyncContext has a start() method that can be used to start Runnable classes.  I believe this kicks off *container* managed threads that run in the DefaultWorkManager and are therefore managed and can be controlled.  Is this not more appropriate as the Container now has visibillity and control over the thread and can restrict the number running?  However, I believe this mechanism is only available within an actual request and cannot be started as part of the init method of a servlet, implying that you need to put some control in place to prevent a new Runnable being scheduled per request.

Secondly:  how should the runnable manage scheduling? The Spec does not favour Applications that manage threads. The concern here is that you would not want the Runnable to implement a loop that tries to execute as fast as possible, else your Container would waste valuable CPU resources.  So how should this be controlled?