It's not a secret anymore!*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Is it thread safe? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Is it thread safe?" Watch "Is it thread safe?" New topic
Author

Is it thread safe?

Barkat Mardhani
Ranch Hand

Joined: Aug 05, 2002
Posts: 787
This is a sample question from TheServerSide.com:


Choose the correct one:
a.) MyServlet is thread safe.
b.) MyServlet is not thread safe because myName is an instance variable.
c.) MyServlet is not thread safe because MyServlet implements SingleThreadModel.
d.) None of the above.
Correct choice
A
Explanation
Choice A is correct. An application is thread safe if it always behaves predictably regardless of the number of concurrent threads running in its process space. The simplest way to ensure that a servlet is thread safe is to implement the SingleThreadModel interface. By implementing this interface, the server guarantees that no more than one thread can execute the service(), doGet(), or doPost() method at a time for a particular servlet instance. This makes the servlet thread safe. Thus even if class MyServlet has instance variables, it is thread safe. Thus A is the correct choice and the other choices are incorrect.

What if container initiates a second instance of same servlet... No two threads can simultanously access a single instance but two threads can access two separate instances. As each instance will want to work on same attribute, this might render itself thread unsafe...
Any comments.
Barkat
Shiva Mantri
Greenhorn

Joined: Dec 30, 2002
Posts: 19
Each object gets its own copy of variables when new instances are created. So, each thread works with its own copy. If you are thinking of displaying something to the screen, like visitCount, which is a member variable, you have to make it static. This way you get uncorrupted visitCount.
[ November 08, 2003: Message edited by: Shiva Mantri ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is it thread safe?