• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sevlet & threads & synchronization  RSS feed

 
Ronald Whalen
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
I have a question. Let's say that I create a DB wrapper class that a servlet can use to access mySQl. Rather than creating a new instance in the doGet method, which I assume means that each thread will create it's own instance, I make it a member variable of the Servlet Class. I initilize it in the init() function. I assume that that means there will be one copy of that DB wrapper class because there is own copy of the servlet. Further assuming that each thread will use that DB wrapper to access the DB. So one copy in memeory for every thread that uses that servlet. I guess that means that there is a possible synch problem where two or more threads could be executing an INSERT function at the same time. Will this create problems? Could this corrupt data? Is it a better idea to have each thread have its own DB wrapper instance? I would like to make the whole process as efficient (server-wise) as possible and as safe as possible.
Any help is greatly appreciated.
Thanks,
Ronald Whalen
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The standard technique is to use a connection pool and checkout a connection when you need it (and check it back in when you're done). JDBC 2.0 (JDK 1.2) automatically uses some connection pooling, but most web containers support more robust pooling.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ronald, I can't tell from your post what your db connection wrapper is actually doing. If all it's doing is storing a Connection object, and not doing anything else that may be unsafe, then you should have no synchronization issues. This is because Connection objects are required to be thread safe.
However, there are two good reasons for moving the connection code from your init() method to your doGet()/doPost() method:
(1) If you have a large number of users all sharing a single db connection, your users may experience poor response time if they're all sharing a single connection.
(2) If you're using transactions, i.e. if you specify con.setAutoCommit(false), then these transactions should not share the same db connection, otherwise you may corrupt your data.
And if you do decide to use multiple connections, then it's best to go with Avery's suggestion and use a connection pool instead of a separate connection per user.
------------------
Miftah Khan
- Sun Certified Programmer for the Java 2 Platform
- Sun Certified Web Component Developer for the J2EE Platform
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!