wood burning stoves 2.0*
The moose likes Servlets and the fly likes Dealing with multi-threading in servlets Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Dealing with multi-threading in servlets" Watch "Dealing with multi-threading in servlets" New topic
Author

Dealing with multi-threading in servlets

Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
As I understand it, because of multi-threading, an instance of a servlet is not thread-safe, or rather the instance variables on the class are not thread-safe.
But when I use a bean in a servlet I have to instantiate it, so surely each thread of in the servlet gets its own instance of the bean and the instance variables are therefore thread-safe?
Any comments, like what have I missed?
thanks
Adam


I have seen things you people would not believe, attack ships on fire off the shoulder of Orion, c-beams sparkling in the dark near the Tennhauser Gate. All these moments will be lost in time, like tears in the rain.
SAFROLE YUTANI
Ranch Hand

Joined: Jul 06, 2001
Posts: 257
As long as you dont use non-static instance variables at the instance level, you'll be safe. You should declare all of your variables inside the methods of the servlet, and each thread accessing your servlet will always get a freash copy of the variables within the method.
SAF
Steven Kors
Ranch Hand

Joined: Jan 30, 2002
Posts: 33
If you have a servlet that is accessing a common variable just use

synchronized(this){
.. code blah
.. code blah
}
This means that if a thread enters this block of code, no other thread can enter this block.
OR
You could implement the singleThreadModel by using the following script..
<%@ page isThreadSafe="false" %>
THis indicates that your code is not thread safe and the resuting servlet should implement SingleThreadedModel. Implementing the SingleThreadModel is fine for low traffic sites but for the higher traffic sites, there will be a definite performance hit.

It is important to note that the following is the default ..
<%@ page isThreadSafe="true" %>
Which means that what ever thread that enters your code, it assumes that your code is synchronized or thread safe

I hope this helps.
[ February 07, 2002: Message edited by: Steven Kors ]

Thanks,
Steven
Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
So far so good. But what if I have a big loop in the servlet, and a variable inside the method of the servlet which gets a new instance of a bean during execution of the method, how about the instance variables in the Bean?
Say two HTTP requests come in simultaneously, then two threads get started in the instance of the servlet.
Each thread instantiates its own copy of the bean, correct?
So the instance variables in the bean should be thread-safe, because each instance of the bean is instantiated and then garbage collected inside the method of the servlet.
Of course I could abuse it by keeping an instance of the bean somewhere and handing it out whenever required, but I'm not planning on that.
Am I correct in my assumption?
Thanks
Adam
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
As long as the reference variable that points to the Bean is a local reference - ie NOT an instance variable or static variable, no other Thread can see it.
Bill
Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
Great. That now I can do what I was planning.
I'm going to have a database access bean which does queries, and I'm going to instantiate it in the method of the servlet. When the bean instantiates, it's going to get itself a connection from a connection pool and keep this in its instance variable.
A transaction will start in the bean on instantiation and I'll have a method on the bean to call to commit it. This way, I won't have to have the connection outside the database access bean.
Adam
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
Be sure you have a way to close that connection no matter what happens. DB connections use a lot of resources and leaving them open is a common point of failure in servlets using DBs.
Bill
Adam Hardy
Ranch Hand

Joined: Oct 09, 2001
Posts: 565
Good point.
There's no such thing as a destructor in Java, is there? I could have a check in the bean destructor to commit and close the connection if it's still open.
I guess I'll just make sure the exception handling is bullet proof.
Thanks for your help, everyone.
Gerry Giese
Ranch Hand

Joined: Aug 02, 2001
Posts: 247
Adam,
Do the following:

This should ensure that you always close the connection.


CJP (Certifiable Java Programmer), AMSE (Anti-Microsoft Software Engineer)
Author of Posts in the Saloon
Gerry Giese
Ranch Hand

Joined: Aug 02, 2001
Posts: 247
Guys, I've also got a question about thread-safety and static variables vs. ServletContext.
I'm building a framework, and I've decided to have an 'Application' object created at AppServer startup that holds various settings from a properties file, some one-time generated data, and a few common methods that are configured using that data, such as logging to an app-specific file.
I want my servlets AND my domain objects to be able to access this object. I created a generic servlet that ALL my application servlets will be required to subclass off of. In the init, I go create the Application object if it hasn't been, and store it in a static variable (Application is also a singleton, just in case). This way ALL my application servlets can access it. I also create a few std methods to wrap the Application object, such as logError(), logMsg(), logDebug(), etc. I also forward doPost() and doGet() to an abstract doProcessing(), but that's beside the point.
So now I have three questions: 1) should I switch from storing the Application object in a static to storing in the ServletContext()?
2) I was planning to try and store the Application object in the static variable of a framework (abstract) class called AppObject. Then each subclass would have a copy for it's use. Should I just pass the Application object in at construction every time? It's my understanding that if the app server restarts, then all the objects will be destroyed, so I don't have to worry about stuff getting out of synch.
3) Do I need to synchronize( ) my calls to the Application object? It won't ever create new objects after the first time, and the only writing/updating of data it does is when I log to a file, and I already have the log class synchronized. Does 'read' access to a class variable need to be synchronized? I may be thinking in SQL too much, where reads don't need 'transactions' (thread synchronization.
Thanks!
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
1. Right off hand I can't think of any reason to switch.
2. Why not just leave it as a static that every class can see? I doubt there is any measurable advantage to giving each object its own copy.
3. No need to synchronize if the data is not changing.
Bill
 
 
subject: Dealing with multi-threading in servlets
 
Similar Threads
session management in tomcat
JavaBeans in Model 2
SingleThreadModel
Singleton or Prototype for DI bean injection?
How does servlet stay active ?