| Author |
Thread Safety
|
Sean Keane
Ranch Hand
Joined: Nov 03, 2010
Posts: 581
|
|
Hi guys, I'm just starting out on this certification and I have a question about the servlet life-cycle and thread-safety - it may seem basic, but I just want to be sure !
From what I've read there will only ever be once instance of my Servlet class created. When the instance is first created the init-method will be called, followed by the service-method, which will in turn call the doGet-method (for example). Then any subsequent calls to this Servlet will result in a new thread be spawning and calling the service-method of the previously created instance of my Servlet class.
So does this mean that methods that my Servlet implements must be thread-safe? For example my doGet-method implementation should be thread-safe as there could be multiple threads executing this method concurrently.
|
SCJP (1.4 | 5.0), OCJP (6.0), OCMJD
|
 |
Sean Keane
Ranch Hand
Joined: Nov 03, 2010
Posts: 581
|
|
|
Ah, I just found the answer to my question. Yes, my Servlet class definitely needs to be thread safe as multiple threads will be accessing it concurrently. Unless my Servlet implements the SingleThreadModel interface - in which case I am guaranteed that only one thread will be executing a method from my Servlet class at any particular moment in time. Sounds good?
|
 |
Ikpefua Jacob-Obinyan
Ranch Hand
Joined: Aug 31, 2010
Posts: 394
|
|
Sean Keane wrote:...Unless my Servlet implements the SingleThreadModel interface - in which case I am guaranteed that only one thread will be executing a method from my Servlet class at any particular moment in time. Sounds good?
Hello Sean... I am afraid it does NOT sound good because the session and context states will be completely vulnerable!... Its like saying oh well I want to synchronize the service method.
A good solution would be;
-synchronyze sessions
-do NOT use instance variables in your Servlet (if you must, then make them 'final')
HtH
Ikpefua
|
OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
|
 |
Sean Keane
Ranch Hand
Joined: Nov 03, 2010
Posts: 581
|
|
|
Thanks Ikpefua, confirms what I was thinking, I should ensure that my Servlet implementation is thread-safe.
|
 |
 |
|
|
subject: Thread Safety
|
|
|