wood burning stoves 2.0*
The moose likes Servlets and the fly likes which variables r thread-safe Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "which variables r thread-safe" Watch "which variables r thread-safe" New topic
Author

which variables r thread-safe

kesava chaitanya
Ranch Hand

Joined: Aug 15, 2001
Posts: 140
Public class TestServlet extends HttpServlet implements SingleThreadModel {
private int x;
public void doPost(HttpRequest req, HttpResponse res){
doPost () .
}

}
In above example instance variable x and request are both thread-safe or else only instance variable is thread safe.
and my next question is
what about class variables,localvariables,context attributes r also thread safe when u implement singlethreadmodel Interface
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60765
    
  65

This is more of a Servlets than a JSP question, so moving this there.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Ram Prasadh Anandaraj
Greenhorn

Joined: Feb 19, 2004
Posts: 4
As far as your example is concerned. I think variable x is thread safe coz
you have implemented SingleThreadModel interface, which means that at any point in time, only one thread can access the service method. Since doPost is invoked by the service method, doPost and the methods that are invoked from within the doPost method are also threadsafe. The instance variable x should also be threadsafe, provided it is being accessed/modified by threadsafe methods.
Hope this helps.
Chris Mathews
Ranch Hand

Joined: Jul 18, 2001
Posts: 2712
SingleThreadModel merely ensures that the Servlet instance is only accessed by a single thread at any time. However, this doesn't stop the Application Server from pooling multiple instances of the Servlet to service multiple concurrent clients... and in fact that is exactly what they do. This of course means that any resource that is shared among Servlets is no longer thread-safe... including the HttpSession and ServletContext. Thus implementing SingleThreadModel merely gives a false sense of security regarding threading issues. For this reason the Servlet 2.4 Expert Group strongly considering deprecating the SingleThreadModel for the latest version of the Servlet Spec... unfortunately it never quite made it in.
I strongly suggest that everyone do themselves a favor and NEVER implement SingleThreadModel. Learn how to write proper thread-safe code... afterall it is not that difficult. Your Applications and your career will thank you for it.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: which variables r thread-safe
 
Similar Threads
Thread and Heap Memory
SingleThreadModel Servlet with class variable
Which Attribute Scopes Are Thread-Safe?
Thread safe servlets
SingleThreadModel