It's not a secret anymore!
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes about SingleThreadModel? 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 "about SingleThreadModel?" Watch "about SingleThreadModel?" New topic

about SingleThreadModel?

Sudarshan Sreenivasan
Ranch Hand

Joined: Jun 28, 2007
Posts: 188

If a servlet implements SingleThreadModel interface does it make the instance variables thread safe .... According to me the answer is no .... because instance variables are stored on the heap & all threads share the same heap !! says in one of its mock tests that instance variables become thread safe by implementing .SingleThreadModel

Please tell me the right answer with an explanation !!

THank you
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

SingleThreadModel, which by the way is deprecated, ensures that only one instance of a servlet's service method will run at a time. So a servlet's instance variables will be thread safe. This would not be true for session variables.

[My Blog]
All roads lead to JavaRanch
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
SingleThreadModel ensures that only one instance of a servlet's service method will run at a time.

Is that really true? Or does it ensure that two threads will never run within the same servlet instance at any one time? I thought there was a possibility that the servlet container allocates more than one instance of a servlet?
Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

My phrasing was bad. I mean that the service method for an instance of a servlet will be protected from multi threading access.

From the Servlet Specification :

SRV.2.2.1 Note About The Single Thread Model
The use of the SingleThreadModel interface guarantees that only one thread at a time will execute in a given servlet instance�s service method. It is important to note that this guarantee only applies to each servlet instance, since the container may choose to pool such objects. Objects that are accessible to more than one servlet instance at a time, such as instances of HttpSession, may be available at any particular time to multiple servlets, including those that implement SingleThreadModel. It is recommended that a developer take other means to resolve those issues instead of implementing this interface, such as avoiding the usage of an instance variable or synchronizing the block of the code accessing those resources. The SingleThreadModel Interface is deprecated in this version of the specification.
[ September 11, 2007: Message edited by: Christophe Verre ]
I agree. Here's the link:
subject: about SingleThreadModel?
It's not a secret anymore!