I was wandering about "what would be the optimal approach for making servlet Thread Safe " It's been said that Single Thread model would work in obvious, but while dealing with many concurrent requests, what would be an optimal approach, is it making an instance SYNC or making DATA (shared) between instances SYNC would work. It would be really helpful if anybody just elaborate on that.
(SYNC - synchronized)
- Thanks - CHI
Joined: Mar 22, 2005
Thread safety is achieved by synchronizing access to shared mutable state. In Java that means objects that can change and which might be accessed by more than one thread at a time.
One example are instance variables - they are shared between threads, so you should avoid them, or make sure that they don't change when multiple threads might access them. Context attributes, and sometimes even session attributes are other examples.
Perhaps because instance (member) variables are dangerous, it's not unusual (where I work) to see get & post methods in servlets run on hundreds of lines with dozens of local variables. That's really ugly! One way around it is to get code out of the servlet into a new object instance that can safely use instance variables. Taken to an extreme, it might look like:
I guess they made a single instance of the servlet run on many threads to avoid creating and destroying servlet instances for every request. This technique puts all that overhead right back in. However, modern JVMs are fast enough at create and gc that I don't worry about it too much.
Can you picture moving some of your logic (maybe not all of it) to other objects like that?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Sep 15, 2006
Yeah I could imagine having another object that use the instance variables, i think it would work to some extent but the question is about making sure that CONCURRENT ACCESS ultimately is THREAD SAFE. this imagination might not surely solve the problem, instead if we make OBJECT(instance) SYNC then it might solve the problem, but again making whole instance again would not be a good idea. instead of doing that,if we do a LOCAL access(as Stan described) with SYNC object instance variables, that may seem plausible. what you think friends ? still in question ?
A very simple rule of thumb is "Don't use instance variables in servlets". When in doubt, create your variables locally, even if it makes the service methods (doPost, doGet..) longer.
Most larger, well written projects move toward a front controller or command pattern to break up and organize the code; which takes care of the long service methods.
If you start synchronizing access to instance variables, you're likely to hurt the performance of your application by causing requests to queue up instead of running concurrently and independently of one another.