File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Alternative to SingleThreadModel Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Alternative to SingleThreadModel" Watch "Alternative to SingleThreadModel" New topic

Alternative to SingleThreadModel

Servin Park

Joined: May 10, 2002
Posts: 26
I am building a wepapp with two servlets (InsertServlet and SelectServlet) that add and retrieve data from database. Since multiple users are going to use this app, I want to make sure each add and retrieve requests don't step on each other. I know I can implement SingleThreadModel for both servlets, but I want to look for alternatives. Any comments or examples will be greatly appreciated. Thank you.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13027
SingleThreadModel has nothing to do with synchronization of database access, and would in fact make it harder. SingleThreadModel just insures that each request has the entire servlet to itself, but the servlet engine can create many instances of the servlet.
What you want is to pass all requests through a single object which handles all database operations. (Often called the Singleton pattern.)
Careful use of synchronized methods in this object will do the trick, and by making it separate from your servlets, it will be easier to debug.
Anthony Villanueva
Ranch Hand

Joined: Mar 22, 2002
Posts: 1055
1. It's usually not recommended to implement SingleThreadModel. Enclose code in synchronized blocks instead. Avoid sharing synchronized objects between concurrent requests.
2. Avoid updating the same data concurrently whenever possible. Use prepared statements for queries that are executed often. Optimize your queries and use cached query results.
3. Use JDBC connection pools whenever available. Different JDBC drivers can generate different amounts of garbage, so use a high-quality JDBC driver.
I agree. Here's the link:
subject: Alternative to SingleThreadModel
It's not a secret anymore!