Thursday, December 9, 2010

Threads and Web Applications

Say you have a standalone (non-web) application where you want to show images. Suppose the images don't have dependencies among each other, so you can load and show each image in a separate thread.
Now say you want to design the same thing as a web application. To make things more concrete, suppose you want to build an application that shows a map of a region as a set (matrix) of tiles, each tile being displayed in a certain, predetermined part of the viewer. Let's call this application randomly 'google maps'.
So we'll have a servlet - say we build this with Java technology - that talks to a certain service from which it gets the corresponding tiles and then generates the page showing these tiles in their proper positions. It is tempting to take the same approach as in the standalone application and let the servlet run threads, each of them dealing with a tile. However, we know running threads from servlets calls for trouble (I'll write about that in separate posts).

So, what to do ? Well, the idea is to run the requests for the tiles in parallel as Ajax requests from - for example, a JavaScript piece of code residing in a JSP page. Each such Ajax request invokes the servlet to retrieve the desired tile. Thus, the servlet remains "pure", unpolluted with dangerous threads and we leave the parallelism and all the other optimizations in the hands of the web container.