• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Is it thread safe?

 
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic