File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Servlets and the fly likes Servlets, Sessions & Thread Safety?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Servlets, Sessions & Thread Safety??" Watch "Servlets, Sessions & Thread Safety??" New topic
Author

Servlets, Sessions & Thread Safety??

DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Im just finishing up a project & doing some testing when a weird thing happened. Let me explain the servlet first. It is an on-site email program with 99% of the features of your basic Hotmail account...yadda yadda. The servlet gets the username of the member from the session variable userID & then uses this string to query the database. I am only testing this on a local machine right now trying to get all the bugs out before I then test it on the server. Note also Im running win98 & tomcat to test. Here's what happened:
I had to browsers open at the same time logged into the site with 2 different username & was basically sending emails back & forth to each other. One email didn't show up as expected so I hit the "inbox" button (displays the contents of their in folder) twice in rapid succession. To my shock the username changed to the username from the other browser & that users email listing appeared! Talk about knocking me over with a feather! Im not sure if this is because Im running a local server & 2 browsers on the same machine or not but I sure want to make sure before this thing is used! Obviously I may have a thread safety issue here but am a little befuddled as to where. From my knowledge of servlets & threads anything within the doPost or doGet & any method called from within these two is supposed to be thread safe.......correct? I have also made sure to set the used variables (username etc.) to null when I declare them & prior to any initialization but that doesnt seem to help.........should I be syncronizing the methods that do these queries & retrieve this info? Like I said this may only be a fluke because of how Im testing it but your input would be gladly accepted here. Im not posting the code because its over 600 lines long but if someone wishes to see exactly what Im doing Id be glad to email it to them........As usual thanks to all!
[This message has been edited by DC Dalton (edited July 14, 2001).]
Marcos Maia
Ranch Hand

Joined: Jan 06, 2001
Posts: 977
Hi,
I have taken this from the servlet tutorial from sun,
something you may note is that usually there is only one instance of a servlet in the server and one new thread for the service, doGet or doPost methods on it, so any instance variables will be shared between clients.
I hope this helps.
the tutorial is at:
http://www.java.sun.com/docs/books/tutorial/servlets/index.html
HTTP servlets are typically capable of serving multiple clients concurrently. If the methods in your servlet do work for clients by accessing a shared resource, then you must either:

Synchronize access to that resource, or

Create a servlet that handles only one client request at a time

Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues during servlet initialization. The server calls the init method once, when the server loads the servlet, and will not call the init method again unless the server is reloading the servlet. The server can not reload a servlet until after the server has destroyed the servlet by running the destroy method.

wael chatila
Greenhorn

Joined: Jul 14, 2001
Posts: 8
Holas!
I've encounted a similar problem while i was testing with several browsers on the same machine.
I was using the session api which i presume you do aswell. My bug was due to uncareful tracing of the different sessions. Maybe you want to take a look there...
regards
wael
PS I would be intressting to see your code!
wael chatila
Greenhorn

Joined: Jul 14, 2001
Posts: 8
PS2 f96wc@efd.lth.se
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
I understand exactly what you are saying & thought I had addressed the matter by eliminating instance variables in the servlet. I am only using local variables! Here's a brief snippet to show you what Im doing here:
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
Statement stmt = null;
Connection conn = null;
PrintWriter out = null;
ResultSet rs = null;
String sesReturn = null;
String userName = null;
try {
HttpSession session = req.getSession(false);
progHtml prog = new progHtml();
HtmlBot bot = new HtmlBot();
int boxNum = 0;
String query = null;
if (session != null){
sesReturn = (String) session.getAttribute("UserID");
res.setContentType ("text/html");
out = res.getWriter();
/////call to methods print results etc.
}
So what am I missing here thats probably blatently obvious (Im so burnt from building this Im lucky I can remember my name!)
Im going to wander through the tutorial you gave me the link for & see if I whats up here........thanks again!
Marcos Maia
Ranch Hand

Joined: Jan 06, 2001
Posts: 977
Hi,
Are this two browsers the same ones(i.e ieexplorer or netscape), I mean 2 windows from the same browser???
wael chatila
Greenhorn

Joined: Jul 14, 2001
Posts: 8
How and where do you call HttpSession.putValue()?
wael chatila
Greenhorn

Joined: Jul 14, 2001
Posts: 8
Good point Marcus, i was just about to test this:
Here is the code
doGet(...)
{
...
HttpSession s=req.getSession(true);
if (s.isNew())
out.println("NEW");
else
out.println("OLD");
}
Results:
* launced up a new browser: NEW
* lanched up a new window (CTRL-N): OLD
-W
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Hi all again.......I just sent the code to Wael. Lots of questions to answer here. I tryed using two instances of IE but also got it too happen when using IE & Netscape or Opera. (I was thinking the same thing myself) The setAttribute("UserID") is done at the time of login in my logIn servlet. I've also made sure that I call the sessions before any response methods & before get the writer. I am using this line in the actual mail Prog for a security check: HttpSession session = req.getSession(false);
As you can see from the above post I also call getAttribute("UserID"); before any response or out methods are called.
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Another note about the dual instances of the same browser thing. I just tested it after implementing the SingleThreadModel on the servlet & still got cross communication problems when using IE for both browsers but when using IE & Netscape to test the problems where gone so obviously using the same browser to test like this on a local machine isn't such a great idea!
Marcos Maia
Ranch Hand

Joined: Jan 06, 2001
Posts: 977
Yes you got a point. Since the session is stored as a cookie, if u use 2 instances of the same browser you�re gonna have an old session like the test Wael did showed us, I�m sure that youre not gonna have problems with your servlet in a real world environment.
PS-We should avoid implementing the SingleThreadModel since it can hurt badly the performance
wael chatila
Greenhorn

Joined: Jul 14, 2001
Posts: 8
I think Marcos is right. In real life you wont have this problem. Probably and somehow your browsers sends the same cookie.
If you still want to completely eilimante this problem you can do some tricks like put in a hidden field, or when you call setAttribute("UserID", XxXX), first call getAttribute("UserID") to see if it already exists.
When i took a look in your code i noticed that you set up a new connection for EVERY reqest. To improve performance you should use connection pooling. Connections should be thread safe.
I like your last statment of "code"
//////////////THANK GOD THIS PAIN IN THE ASS IS DONE!!!
-W
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Thanks for looking at the code Wael! I hope you & Marcos are right. I was using the dbConnectionBroker on my servlets but I ran into a problem when I tested them on my server (See this post in the jdbc section http://www.javaranch.com/ubb/Forum3/HTML/001228.html ) and havent figured it out yet so Im using standard connection methods until I figure that one out. As I said in my email to you this is my first time attempting servlets of this magnitude so Im a tad gun shy about security. Thanks again to all for looking at this!
Subbu Aswathanarayan
Ranch Hand

Joined: Jun 22, 2001
Posts: 73
Originally posted by DC Dalton:
Thanks for looking at the code Wael! I hope you & Marcos are right. I was using the dbConnectionBroker on my servlets but I ran into a problem when I tested them on my server (See this post in the jdbc section http://www.javaranch.com/ubb/Forum3/HTML/001228.html ) and havent figured it out yet so Im using standard connection methods until I figure that one out. As I said in my email to you this is my first time attempting servlets of this magnitude so Im a tad gun shy about security. Thanks again to all for looking at this!

Hi DC,
I am also working on a similar project as you are.I started using DbConnectionBroker after seeing Carl Trusiak's and ur posts.Initially I had problems but ur posts and a lot of help from Carl helped solve my problem.DbConnectonBroker works fine now.Infact I have started using JDBCGlobalBroker without any problems.
Subbu


Subbu
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Hey Subbu. Id love to know what you ended up doing to get a broker running. If you look at this other post I have I think you'll see the problem Im having. It's all good on my local machine but blows right up on my server. I dont want to change this post around to a jdbc problem so maybe you can look at the other one......thanks DC
Subbu Aswathanarayan
Ranch Hand

Joined: Jun 22, 2001
Posts: 73
Hey DC,
I think you are not placing the class files in the correct directory.
u need to place the dbConnectionBroker class file in <server root dir>/lib/com/javaexchange/dbConnectionBroker/ as well as in jdk/lib/com/javaexchange/dbConnectionBroker/
i am pretty sure u must have done this already but just making sure.
i was also getting an error similar to urs but once i placed the files in the above directory everything started working fine.
let me know if that helps.
Subbu
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
I have them in the root/lib/etc but not in the jdk/lib......Ill try that......Thanks!
Steve Snodgrass
Greenhorn

Joined: Jun 12, 2001
Posts: 27
I believe that in IE 5+ whether or not the session is shared between the two browsers depends upon how you open the second browser. If you open it from within the browser using File/Open then the session is shared and the type of testing you are doing will not work. If you instead open the browser from the Start/Programs then a new session is created for the new browser and there should not be any interference. I do this kind of testing all the time. If you have a device to monitor HTTP requests you should be able to see the session ID in the header to confirm that they are infact different sessions.
Elango _maragatham
Greenhorn

Joined: Jul 16, 2001
Posts: 1
Once i faced the same problem when running Server in the same machine .
How i solved this is in the IE settings check launch browser in separate process
also in general tab click every visit to page radio and try the same code?
Hope this may help
Raghav Sam
Ranch Hand

Joined: Apr 12, 2001
Posts: 412
Originally posted by Steve Snodgrass:
I believe that in IE 5+ whether or not the session is shared between the two browsers depends upon how you open the second browser. If you open it from within the browser using File/Open then the session is shared and the type of testing you are doing will not work. If you instead open the browser from the Start/Programs then a new session is created for the new browser and there should not be any interference. I do this kind of testing all the time. If you have a device to monitor HTTP requests you should be able to see the session ID in the header to confirm that they are infact different sessions.

That's true. I think the question <a href="http://www.jspinsider.com/faq/22.view">Why do two different browsers share the same session?</a> answered by Jayson Falkner at www.jspinsider.com puts things in perspective.
------------------
Raghav.


Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind.<br />- Dr. Seuss
Raghav Sam
Ranch Hand

Joined: Apr 12, 2001
Posts: 412
Originally posted by Steve Snodgrass:
I believe that in IE 5+ whether or not the session is shared between the two browsers depends upon how you open the second browser. If you open it from within the browser using File/Open then the session is shared and the type of testing you are doing will not work. If you instead open the browser from the Start/Programs then a new session is created for the new browser and there should not be any interference. I do this kind of testing all the time. If you have a device to monitor HTTP requests you should be able to see the session ID in the header to confirm that they are infact different sessions.

That's true. I think the question Why do two different browsers share the same session? answered by Jayson Falkner at www.jspinsider.com puts things in perspective.
------------------
Raghav.
[This message has been edited by Raghav Sam (edited July 17, 2001).]
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
Well it's nice to see Im not the only one that has seen this happen (like little green men on a country road........nobody believes you!). The funny thing about that article is that I ALWAYS use two instances of a browser, never using control n or file open. But then again we are dealing with IE & Microsoft here. If anything can possibly screw up in a browser thats the one to do it.......not that Microsoft isnt a great company....YEAH RIGHT! nudge nudge wink wink say no more. Im gonna try the tweaks to IE mentioned above & see if they help......we start actual server tests next week so that will be the real test......Ill keep you all updated
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Servlets, Sessions & Thread Safety??
 
Similar Threads
Help !!!!!!! Connection problems from you know where!
jdbc connection AGGRAVATION!! Can you help?
First time applet
Catching a Class not Found Exception in Resin
testing servlet thread safety