• Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronization

 
Ann Kanu
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the below 2 methods in my DBConnection class which establishes my database connection from a connection pool. If I am using servlets, and inside my service() method, I declare and initialize a class A, which in turn calls the DBConnection class to establish database connection, then where in my below code do I need to synchronize the methods. I havent written any programs which use threads though I use servlets quite a bit (I keep all my variables in the service method). Please help !!
Also, if anyone knows of a good book/website which has good examples of multithreading and servlets, please let me know.
public DBConnection( boolean usePool ) {
if ( usePool ) {
this.connection = poolConnection();
} else {
this.connection = openDBConnection();
}
}
private Connection poolConnection() {
try {
Class.forName(driver).newInstance();
this.connection = DriverManager.getConnection(poolName);
} catch ( Exception ex ) {
//log error messages
}
return this.connection;
}
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You synchronize resources that are going to be shared by more than one thread and I don't see anything in your code that is a single resource being shared. If you had an ArrayList where you were keeping PoolConnections, for example, you'd want synchronized blocks around where you are doing get/put on the ArrayList. The Java Tutorial has a good introduction on the strategies and pitfalls of threads. The information there applies to servlets as to any Java app.
 
Ann Kanu
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Joe, thanks for the reply.
So, the multithreading issues of accessing connections from a connection pool are maintained by the app server. Is that right.
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That depends on the app server's implementation. It would make sense, wouldn't it?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!