Joseph McCarthy from IBM Ireland has written a tutorial
called "Using Comet for asynchronous user notification of autonomous server thread progression" about how to use polling and Comet (long polling) in Java with the ItsNat Java web framework to asynchronously notify end users through web the progression of
an autonomous thread (not a web thread) executing a long task in parallel.
The problem selected is to calculate the PI number through Gregory-Leibniz
series. This calculation takes very much time if you want high precision.
This calculation "cannot" be executed in a single web request because the end user cannot see how the calculation is progressing and cannot estimate how much time remains.
This is because an autonomous thread is created in server to accomplish this task. In this case the calculation is finished when the PI estimation is near enough to the Java PI constant (Math.PI). In some way this example "validates" the Gregory-Leibniz series.
The objective is monitoring by web this server thread with no user interaction, periodically obtaining the estimated value and of course asynchronously notifying to the end user when the calculation has finished. As a bonus, the user can start and stop the server thread through web buttons.
The article has two parts/approaches:
1) In the first part the "polling" technique is used (through the use of a meta refresh directive) alongside AJAX to query the thread state, conventional page navigation technology to start and stop the thread and global variables to hold the thread and calculation states. No specific web framework is used (just servlets and JSPs).
2) The second part uses Comet (long-polling) provided by the ItsNat
framework. In this case the application is Single Page Interface
and the thread is only attached to the user's page.
For Comet ItsNat provides a CometNotifier object "attached" to the web page, this object has a method CometNotifier.notifyClient(), when the autonomous thread calls this method, an special DOM event is fired in server and dispatched to event listeners registered on the CometNotifier, in this event listener any DOM change performed in server (because ItsNat simulates a W3C Java browser in server) is automatically and asynchronously synchronized in client DOM.
Because the CometNotifier can be stopped and recreated, the CometNotifier life cycle is the same as the autonomous thread, ItsNat managed buttons are used to start/stop the server thread and CometNotifier. In this case when the start and stop buttons are clicked, Java W3C events are received in server and dispatched to the W3C event listeners registered on the symmetric buttons in server, this is the normal use of ItsNat.
Note: the original article has an important visual problem, to read it use MSIE 6 (yes in this case a non-W3C CSS compliant browser is great) or FireFox disabling styles (View/Page Style/No Style).