File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Using DataSource Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Using DataSource Question" Watch "Using DataSource Question" New topic

Using DataSource Question

Philip Hung

Joined: Dec 11, 2001
Posts: 10
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

Joined: Oct 01, 2001
Posts: 2968

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

Joined: Dec 11, 2001
Posts: 10
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.
I agree. Here's the link:
subject: Using DataSource Question
jQuery in Action, 3rd edition