File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Safety

 
Sean Keane
Ranch Hand
Posts: 582
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sean Keane
Ranch Hand
Posts: 582
Chrome Eclipse IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 394
Eclipse IDE Java Oracle
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Sean Keane
Ranch Hand
Posts: 582
Chrome Eclipse IDE Java
  • 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ikpefua, confirms what I was thinking, I should ensure that my Servlet implementation is thread-safe.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic