This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
That's the magic of app servers: You have one JVM process that stays alive--I think it's one per Web Application?--and that one process automatically spawns threads as needed, to serve the different requests.
You, as the developer, don't have to write an ounce of thread-creation code because the app server does it for you. In fact, if your servlet doesn't have any member variables or share objects across the application you wouldn't even have to think about concurrency.
Except many servlets do evolve to share something, which is when things get ugly pretty quickly and coders have to tread far more cautiously.
There is only ever one instance of a servlet running in memory. Per request, the Container creates a new thread with its own stack, appends the request and response objects to it, and runs the servlet's service method. Once the method has completed, the response object is sent to the client and the thread is destroyed.
Indeed. There are circumstances where more than one instance of a servlet can be loaded, but that has no bearing on how Servlets need to be written in a thread-safe manner.
Joined: Nov 20, 2008
Bear Bibeault wrote:Indeed. There are circumstances where more than one instance of a servlet can be loaded, but that has no bearing on how Servlets need to be written in a thread-safe manner.
If you don't use servlet attributes and/or only use final attributes then you don't have threading issue. But if you do use servlet attributes and manipulate these attributes within the service method then you do have to worry or should consider changing your design.
Ryan Beckett wrote:I am well aware that only local variables and request attributes are thread safe. What is a scenario that would allow multiple instances of a servlet to be loaded?
The same servlet class can be declared multiple times in the deployment descriptor, and each will cause a servlet instance to be loaded. Additionally, the servlet specification allows for the container to decide to instantiate as many instances as it would like based upon its internal implementation details.