Detect connection leaks in pooled DataSource

232 views Asked by At

I am writing code in order to detect whether my application is leaking connections or not. I use c3p0 as connection pool.

In my unit tests, I have tried to create a @Rule that checks, at the end of the tests, that there are no pending connections. This will help me find code that is forgetting to close Connections. For now, this has to work with c3p0 pool.

I have written the following code:

public class ConnectionLeakChecker extends Verifier
{

    private DataSource dataSource;

    @Override
    protected void verify() throws Throwable
    {
        if (dataSource == null)
            return;

        if (dataSource instanceof PooledDataSource)
        {
            PooledDataSource pool = (PooledDataSource) dataSource;
            int numBusyConnectionsDefaultUser = pool.getNumBusyConnectionsDefaultUser();
            if (numBusyConnectionsDefaultUser > 0)
                throw new AssertionError("Connections not released: " + numBusyConnectionsDefaultUser);
        }
        else
            throw new AssertionError("Database pool type not supported: " + dataSource.getClass().getCanonicalName());
    }

    public DataSource getDataSource()
    {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource)
    {
        this.dataSource = dataSource;
    }
}

However, when instantiating the component as @Rule, it will randomly detect one pending connections (in my current tests, I use only one).

Some tests will have a connection hanging, others not. If I run a failing test alone, I usually don't get any more complaints.

I think the getNumBusyConnectionsDefaultUser() method does not do what I would like to achieve.

Somebody help?

0

There are 0 answers