ace ace - 8 days ago 8
Java Question

How does multithreading work for a java Servlet?

Java Servlet life cycle is managed by the servlet container. When first web request comes in, the container will load the Servlet class, calls its init method, then calls its service method to process the web request. It says there can be only one instance of servlet class. The container creates multiple threads and manages these threads to process multiple web requests (this is what I know from my knowledge). But I want to understand, how multiple threads are running and processing multiple simultaneous web requests given that there is only one instance of the servlet class. Can some one shed light on this?

Answer

An object instance('s methods) can be called simultaneously by more than one thread. This isn't specific for servlets though and is true in general.

What happens when this occurs? Each thread will still have their own stack, which means, each thread will have a different copy of local variables to work on. As a result there will be no interference between threads and you won't have to worry about concurrent calls. Only when a shared resource, e.g. instance/class variable is accessed, there can be a problem. Same thing if instance/class variable is directly accessed concurrently.

EJBs in contrast do exactly what you seem to suggest. The EJB container makes sure that only one thread enters an EJB instance at a time, and hence an EJB programmer doesn't have to worry about concurrency so long as he/she doesn't break the EJB programming contract. There is no reason why the servlet spec didn't do this. Most likely no body came up with it during the meetings? It does have the advantage though that you can use a more efficient concurrency management than EJB's "one thread per instance".