File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes EJB and other Java EE Technologies and the fly likes Synchronization in DAOs ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Synchronization in DAOs ?" Watch "Synchronization in DAOs ?" New topic

Synchronization in DAOs ?

Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

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 ?
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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 ]
Hussein Baghdadi
clojure forum advocate

Joined: Nov 08, 2003
Posts: 3479

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 ?
Adeel Ansari
Ranch Hand

Joined: Aug 15, 2004
Posts: 2874
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.

tell me if it is not like that. plz
I agree. Here's the link:
subject: Synchronization in DAOs ?
It's not a secret anymore!