Search code examples
javadatabase-connectiondatasourceconnection-poolingapache-commons-dbcp

How does the Java BasicDataSource create new connections to a database when the database password is changed?


I'm currently working on a problem where I have a running Java 6 application that when first starts up, creates a BasicDataSource which when first created, stores all the necessary information needed to create connections to the database like so:

DS.setUserName(username);
DS.setPassword(password);
DS.setUrl(url);
DS.setMinIdle(minIdle);
.
.
.

It then creates a pool of connections to the database using the set properties. The BasicDataSource is then stored in a Map which is then returned to the calling method every time it is required like so:

if (dataSources.contains(databaseDS)) {
    return dataSources.get(databaseDS.getConnection());
}

My understanding is that the BasicDataSource's connection pool has live connections to the database that don't require the use of the password to log into the database but rather that connection already has a session established with the database. These connections will be returned to the calling method which don't need to re-authenticate with the database.

However, when the database password is updated and a new connection is needed/spawned, how does the BasicDataSource create that connection? Does it try to authenticate with the database with the password that is stored in the BasicDataSource to get a new connection?

Thank you


Solution

  • So in the end, I ended up deciding on synchronizing the pulling of connections from the pool. When we're out of connections and the BasicDataSource needs to authenticate again for a new connection, we will create a new connection to the database. However, when the password has changed, we'll get an authentication error to the database and I will then drop the BasicDataSource from the Map of DataSources. After this, I then create a new BasicDataSource with the new password.

    The reason for synchronizing (if this makes no sense could someone slap some sense into me?) is so that failing authentication to the database only happens once so we don't end up trying to hit the database too many times with the wrong password. The previous connections will grow stale and eventually get cleaned up which then the object should get garbage collected.