• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using DataSource Question

 
Philip Hung
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given two DataSource objects (DS1 and DS2) created from the same Context object and assuming both are configured to connect to the same connection pool. Is it possible that the two DataSource will return the same connection?
Connection con1 = DS1.getConnection();
Connection con2 = DS2.getConnection();
boolean test = con1 == con2;
Is it possible for the boolean variable test to be "true"? In theory, this shouldn't be possible since the connection pool should be managing which connection it gives out, so it will know what connection are "in use". Is this implementation specific? I'm using a Websphere (4.0) managed pool and it appears that I'm getting the same connection. How do I prevent this from happening?
Please help. Thanks in advance.
 
Greg Charles
Sheriff
Posts: 2993
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This shouldn't be possible. The connection does come from a pool, but a single client should have exclusive use of it until it is closed. When the client calls close on this connection, it isn't closed in the traditional sense, but rather returned to the pool. Only then could another client retrieve it. What makes you think you are getting the same connection simultaneously in your two clients?
 
Philip Hung
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well I found the problem already and you are right it is impossible for the DataSource to return the same connection given the underlying pool management behind it. I've taken a look at the connection wrapper class I was using and realized that it was not thread safe, making it return the same connection.
Basically the class has an instance Connection variable which is set during calls to connect().
public void connect(){
:
:
connection = myDataSource.getConnection();
:
}
and returns the connection through a getter
public Connection getConnection(){
return connection;
}
This probably will work fine in most cases, however I was using this class in a multi-threaded fashion such that if two threads simultaneously call connect(), the last connection retrieved will have overwritten the initial connection stored in the instance variable. Resulting in my using the same connection in both threads which is a violation of the latest J2EE specification.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic