Search code examples
javaconnection-pooling

is public Connection getInstance(String databasename); a form of connection pooling?


In a javase database application, I process a lot of short-lived object (say accounting documents like bills etc.).
Processing each object consists in opening a connection to a database and looking up for some data. Not all objects are looked up on the same database, but i select a specific database according to some object property, so i'll end up having several connections opened.
What i actually need is no more than one connection for each database.
So I've done something like this:

public MyPool {

    Map<String, Connection> activeConnections = new TreeMap<String, Connection>();

    public Connection getConnection(String database_name) throws SQLException {

    if (activeConnections.containsKey(database_name)) {
        return activeConnections.get(database_name);
    }

    //Retrive the configuration data from a configuration object
    ConnectionConfig c = Configuration.getConnectionConfig(database_name);

    Connection connection = DriverManager.getConnection(c.url, c.user, c.password);

    return connection;

}

The questions are:
1) Since I see around a lot of pooling libraries, DBCP, c3p0 and others: what is the point of all those libraries, what do they add to a "basic" approach like this?
Tutorials like this doesn't help much in responding this question, since the basic solution exposed here fits perfectly their definition of connection pooling.

2) This is a piece of code that will be "exposed" to other developers, that in turn may develop procedures to retrieve data from databases with different structures, probably getting connections from this "pool object".
Is it correct, in the docs and in the code, referring to it as a "pool", or is it something different, so that calling "pool" would be misleading?


Solution

  • Your code isn't a connection pool implementation in the colloquial use of the term since each datasource only has a single physical connection. The concept behind object pooling (in this case, the object is a connection) is that some objects require overhead to configure. In the case of a connection pool, as you know, a database connection must be opened before you can talk to the database.

    The difference here is that your code isn't thread safe for a concurrent environment like the popular connection pool implementations you've mentioned. Applications running in high concurrency circumstances like the web shouldn't need to absorb the overhead of establishing a connection on each request. Instead, a pool of open connections is maintained and when the request has finished working on the connection, it is returned to the pool for subsequent requests to make use of.

    This is required because connections are stateful. You can't have multiple requests sharing the same connection at the same time and guarantee any sort of reasonable transaction semantics.