开发者

Close connection to DB does not close all connections

I have connection leak to DB in my code. The funny thing is that when I debug, all the connections are closed successfully (or when I do Thread.Sleep(100) ). but without that there is开发者_StackOverflow always one connection that stays! Can you tell what is the problem here?

ComboPooledDataSource dataSource = null;

        try {
            dataSource = dataSourceFactory.getDataSource(dbType, dbProps);


            dataSource.getConnection();

        } finally {
            if (dataSource != null)
            {
                try
                {
                    log.debug("validate() : Closing SQL connection pool");
                    DataSources.destroy(dataSource);
                    dataSource = null;
                    log.debug("validate() : SQL connection pool is closed");

                }
                catch (Exception e)
                {
                    log.error("validate() : Error closing data source", e);
                }
            }       
        }


I think that your problem is related to this question regarding C3P0. I guess a Thread.sleep(delay) before DataSources.destroy(dataSource) solves your problem. I also guess that you know that some connection has been left intact checking your MySQL logs. However, apart from that in your case I would suggest to manually close the connection apart from the datasource which is something to do after every use of it. So I would suggest the following modification:

    ComboPooledDataSource dataSource = null;
    Connection connection = null;
    try {
        dataSource = dataSourceFactory.getDataSource(dbType, dbProps);
        // Get a connection from the datasource
        connection = dataSource.getConnection();
    } finally {
        if (connection!=null){
            connection.close();
        }
        if (dataSource != null) {
            try {
                log.debug("validate() : Closing SQL connection pool");
                DataSources.destroy(dataSource);
                dataSource = null;
                log.debug("validate() : SQL connection pool is closed");
            } catch (Exception e) {
                log.error("validate() : Error closing data source", e);
            }
        }       
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜