Hi all. I have developed a small J2EE application. to access the database from servlets and EJB, I used DAO pattern. because we have only one instance of a given servlet, should I consider the synchronization issues in my DAOs ? given the following code in a servlet's doPost( ) :
what to do here ? surroned the previous code with synchronized statement ? or add the synchronized modifier to each method of MySqlCustomerDAO class ? or I don't need to modify anything ? thanks.
Peter den Haan
Joined: Apr 20, 2000
Where your CustomerDAO has no mutable state - i.e. its instance variables consist of collaborators and configuration information that never changes - you do not need to do anything. The code is threadsafe as is.
Any code that modifies state - for example looking up a DataSource in JNDI and storing it in an instance variable - needs to be synchronized.
You certainly do want to avoid putting the JDBC operations themselves inside a synchronized block or synchronized method. That's unnecessary and, since such operations can take a comparatively long time, the lock contention would potentially kill performance.
- Peter [ September 02, 2004: Message edited by: Peter den Haan ]
Thanks alot. but I have some more questions : 1. given MySqlCustomerDAO's insertCustomer( ) method, this method will try to insert a new row in the database, and we have only single servlet with concurrents users, why we don't need to synchronize insertCustomer( ) method (or using a statement) ? because we rely on the database insolation's level ? 2. assume we don't use DAO in our servlet to access the database, instead of, we will use a method defiened in the servlet class.
should I use insertCustomer( ) inside synchronized statement ? or rely on database's isolation level ? thanks.
Joined: Aug 15, 2004
since you are instantiating your DAO on every request, the synchronized method or a synchronized block in your DAO doesn't make sense.
synchronized works for multiple threads of the same instance. if i am not wrong.
you can instantiate your DAO in servlet.init() method. and then use synchronized blocks inside your update methods of DAO.