Close connection to DB does not close all connections

冷暖自知 提交于 2019-12-13 06:44:55

问题


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 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);
                }
            }       
        }

回答1:


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);
            }
        }       
    }


来源:https://stackoverflow.com/questions/5075824/close-connection-to-db-does-not-close-all-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!