We had a servlet that implemented MultipleThreadModel but had some disasters when multiple users started getting each other's data and transactions mixed up. We've gone back to SingleThreadModel but would like to try to get MultipleThreadModel to work. I think we need cache/pool the JDBC connections, but could someone comment on how that is done?
Hello: I am new to Servlet/JSP, do not know much. So now how do you judge weather to use MultiThreadModel or SingleThreadModel? I know for SingleThreadModel, I need to pool the servlet instances, and each request is served by one instance, not a thread. It seems to be easier to develop, because I do not need to write much synchronizing codes, but It says in my book that this approach is going to be very slow. Is it true? How to decide which one is a better approach for a system? Thanks.
one thing I'd be careful about is 'MultiThreadModel' because this is not mentioned in any spec I've read. There is such a thing as 'SingleThreadModel', but here is the thing to remember about servlets and the fact they are multi-threaded....
Just avoid using globals. ie: class variables. Even if your container sends two requests through your servlet at once.. ie: servlets are multi-thread enabled... the only 'synchronizing' issues you will need to worry about are on *class* variables.
Here's a big snip from the spec in case this thread helps others: the bolding (**) is mine:
[This message has been edited by Mike Curwen (edited October 16, 2001).]
While the SingleThreadModel interface lets the container know that the ENTIRE SERVLET (or JSP) must be serialized, the default is to run multithreaded. In that case, all the standard rules for multithreaded code apply - in particular, that no object of class scope should be accessed without suitable guards (synchronization). Databases are an even stickier problem, since they may be modified outside of the Java environment, and thus you may need additional syncronization. Some of the things that you'd normally do: 1. Use database connection pools (lowers overhead) 2. Use transaction management 3. NEVER access modifiable class-wide or singleton objects directly. Always use synchronized methods. Generally, you want to synchronize on a fairly fine level in order to reduce the amount of time the different threads run blocked. Don't overdo it though - synchronization has its own overhead.
An IDE is no substitute for an Intelligent Developer.