Hello, 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.
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. Bill
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.