Kohei Nozaki
Kohei Nozaki

Reputation: 1154

JDBC connection pooling library which can handle connections that go idle often nicely?

Let’s say there is this code which lives in a server side backend:

class Foo {
    void doSomething() {
        try (Connection c = dataSource.getConnection()) {
            executeSQL(c);
            externalApiCall(); // this can be slow
            executeSQL(c);
        }
    }
}

The problem here is that externalApiCall() can be very slow, and it keeps a lot of database connections open (even though it’s not used) and it can lead to running out of the maximum number of the connections. It will be harmful to other parts of my app which don’t depend on any external API, and I want to avoid this.

The code above is simplified and in reality I use something like a ServletFilter which puts Connection into ThreadLocal when it receives a http request, so it’s difficult to change the overall mechanism which opens a Connection at the beginning of business logic.

So my question is: isn’t there any nice connection pooling library, a wrapper or something that can handle such a situation nicely? For example, something which opens a real database connection only when a Statement object is created and close the connection afterwards automatically when the Statement is closed. Currently I use Tomcat DBCP.

Upvotes: 0

Views: 192

Answers (1)

Coder
Coder

Reputation: 52

Use cp3 connection pooling.

The property max_idle_time may satisfy your requirements here.

  • maxIdleTime

Default: 0

Seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire.

For more info, refer https://www.mchange.com/projects/c3p0/

Upvotes: 0

Related Questions