• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronization in DAOs ?

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic