We have an application that uses the JSP/Servlet model. Info from the jsp is submitted to a servlet that deals with business objects and DAO's. We keep some information in HttpSession objects and recently we have discovered that the sessions can get mixed up if there are multiple request coming into the servlet at close time intervals. For example if three of us try to log in, I will log in as somone else and someone will log in as me, etc....This is due to the fact that from my understanding sessions are application wide and all threads issued by the servlet have access to those resources. Therefore when a few threads are running concurrently they can “get confused” as to which session belongs to who.
We have found 2 solutions to this problem.
1. synchronizing the servlets service(). The problem with this is that it lock the service method until the first thread has finished working with it, therefore with many concurrent users the queue will grow significantly and that will hurt the performance
2. Having the servlet implement SingleThreadModel interface. Not sure how this works but from what I understand it causes the servlet container to create a pool of servlet instances and execute one thread in each instance for each request… This seems to have a better performance then synchronizing the service method (as per the tests that we ran) but I can see how this can soon become very costly if the server has to have 500 servlet instances in the pool. The other thing that worries me is that I am not sure how and why this really works…
From the research done it seems that both the methods mentioned are not very good and synchronizing access to the shared resource should be the way to go but putting a synchronized scriplet around accessing the session doesn’t do jack….No one really mentions a working solution.
Please let me know if any of you have encountered a similar problem and how you dealt with it. Also if anyone could shine some light on the singleThreadModel interface, I would greatly appreciate it!