헤르메스 LIFE

[오픈소스] DBConnectionManager.java 본문

Core Java

[오픈소스] DBConnectionManager.java

헤르메스의날개 2022. 8. 15. 23:43
728x90

DB Connection Pool 을 프로그램을 이용해서 처리할 경우가 앞으로 있을지 모르겠지만, 소스를 찾아서 옮겨봅니다.

워낙 오래된 소스이기도 하고, GNU 라이센스라 나중에 사용이 될까..? 하는 마음에 가져왔습니다.

출처 : http://alvinalexander.com/java/jwarehouse/mvnforum-1.0.0-rc4_04-src/myvietnam/src/net/myvietnam/mvncore/db/index.shtml


  • DBConnectionManager.java
/*
* $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/db/DBConnectionManager.java,v 1.13 2005/01/26 04:54:26 minhnn Exp $
* $Author: minhnn $
* $Revision: 1.13 $
* $Date: 2005/01/26 04:54:26 $
*
* ====================================================================
*
* Copyright (C) 2002-2005 by MyVietnam.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* All copyright notices regarding MyVietnam and MyVietnam CoreLib
* MUST remain intact in the scripts and source code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
* Correspondence and Marketing Questions can be sent to:
* info@MyVietnam.net
*
* @author: Minh Nguyen  minhnn@MyVietnam.net
* @author: Mai  Nguyen  mai.nh@MyVietnam.net
*/
package net.myvietnam.mvncore.db;

import java.sql.*;
import java.util.Enumeration;
import java.util.Vector;

import net.myvietnam.mvncore.MVNCoreConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* This class is a Singleton that provides access to the
* connection pool. A client gets access to the single
* instance through the static getInstance() method
* and can then check-out and check-in connections from a pool.
* When the client shuts down it should call the release() method
* to close all opened connections and do other clean up.
*/
class DBConnectionManager {

    private static Log log = LogFactory.getLog(DBConnectionManager.class);

    private static final int TIME_BETWEEN_RETRIES = 500; // O.5 second

    // static variable
    static private DBConnectionManager instance = null;      // The single instance

    // instance variable
    private DBConnectionPool pool = null;// please be careful if u want to make this variable static

    /**
    * A private constructor since this is a Singleton
    * Note: This constructor is lightweight since DBConnectionPool is lightweight,
    *      so no connection is created until the first time getConnection() is called
    */
    private DBConnectionManager(DBOptions option) {
        try {
            Class.forName(option.driverClassName).newInstance();
        } catch (Exception e) {
            log.fatal("DBConnectionManager: Unable to load driver = " + option.driverClassName);
        }

        //always new the pool because pool is an instance variable
        pool = new DBConnectionPool(option.databaseURL, option.databaseUser, option.databasePassword, option.maxConnection);
    }

    private DBConnectionManager() {
        String driverClassName = MVNCoreConfig.getDriverClassName();
        try {
            Class.forName(driverClassName).newInstance();
        } catch (Exception e) {
            log.fatal("DBConnectionManager: Unable to load driver = " + driverClassName);
        }

        String url = MVNCoreConfig.getDatabaseURL();
        String user = MVNCoreConfig.getDatabaseUser();
        String password = MVNCoreConfig.getDatabasePassword();
        int maxConnection = MVNCoreConfig.getMaxConnection();

        //always new the pool because pool is an instance variable
        pool = new DBConnectionPool(url, user, password, maxConnection);
    }

    /**
    * Returns the single instance, creating one if it's the
    * first time this method is called.
    *
    * @return DBConnectionManager The single instance.
    */
    /*
    public static synchronized DBConnectionManager getInstance() {
        if (instance == null) {
            DBOptions option = new DBOptions();
            instance = new DBConnectionManager(option);
        }
        return instance;
    }*/

    /**
    * Returns the single instance, creating one if it's the
    * first time this method is called.
    *
    * @return DBConnectionManager The single instance.
    */
    /*
    private static synchronized DBConnectionManager getInstance(DBOptions option) {
        if (instance == null) {
            if (option == null) {
                option = new DBOptions();
            }
            instance = new DBConnectionManager(option);
        }
        return instance;
    }*/

    public static synchronized DBConnectionManager getInstance(boolean useConfig) {
        if (instance == null) {
            instance = new DBConnectionManager();
        }
        return instance;
    }

    /**
    * Returns a connection to the pool.
    *
    * @param con The Connection
    */
    void freeConnection(Connection con) {
        pool.freeConnection(con);
    }

    /**
    * Returns an open connection. If no one is available, and the max
    * number of connections has not been reached, a new connection is
    * created.
    *
    * @return Connection The connection or null
    */
    Connection getConnection() {
        return pool.getConnection();
    }

    /**
    * Returns an open connection. If no one is available, and the max
    * number of connections has not been reached, a new connection is
    * created. If the max number has been reached, waits until one
    * is available or the specified time has elapsed.
    *
    * @param time The number of milliseconds to wait
    * @return Connection The connection or null
    */
    Connection getConnection(long time) {
        return pool.getConnection(time);
    }

    /**
    * Closes all open connections.
    * @return true if the pool is empty and balance
    *        false if the pool has returned some connection to outside
    */
    boolean release() {
        return pool.release();
    }

    /**
    * This inner class represents a connection pool. It creates new
    * connections on demand, up to a max number if specified.
    * It also checks to make sure that the connection is still open
    * before it is returned to a client.
    */
    class DBConnectionPool {
        private int checkedOut  = 0;//NOTE: this variable should be changed in synchronized method only
        private Vector freeConnections = new Vector();

        private int    maxConn  = 0;
        private String password = null;
        private String URL      = null;
        private String user    = null;

        /**
        * Creates new connection pool.
        * NOTE: new an instance of this class is lightweight since it does not create any connections
        *
        * @param URL The JDBC URL for the database
        * @param user The database user, or null
        * @param password The database user password, or null
        * @param maxConn The maximal number of connections, or 0 for no limit
        */
        public DBConnectionPool(String URL, String user, String password, int maxConn) {
            this.URL = URL;
            this.user = user;
            this.password = password;
            this.maxConn = maxConn;
        }

        /**
        * Checks in a connection to the pool. Notify other Threads that
        * may be waiting for a connection.
        *
        * @todo: Maybe we dont need notifyAll(); ???
        *
        * @param con The connection to check in
        */
        synchronized void freeConnection(Connection con) {
            // Put the connection at the end of the Vector
            if (con != null) {//make sure that the connection is not null
                if (checkedOut <= 0) {
                    // this means that connection is open too much
                    // There are 2 cases:
                    // 1. Not get from this connection pool (maybe get directly)
                    // 2. this connection is gotten and then the whole pool is released
                    // In these case, just close the connection
                    try {
                        log.debug("DBConnectionManager: about to close the orphan connection.");
                        con.close();
                    } catch (SQLException ex) { }
                } else {
                    // Return this connection to the pool
                    // note that we dont have to check if the connection is not connected
                    // this will be check in the getConnection method
                    freeConnections.addElement(con);
                    // FIXME: posible negative value
                    // NOTE: checkOut should never be negative here
                    checkedOut--; // NOTE: this number can be negative (in case connection does not come from the pool)
                    notifyAll(); // can I remove it ???
                }
            }
        }

        /**
        * Checks out a connection from the pool. If no free connection
        * is available, a new connection is created unless the max
        * number of connections has been reached. If a free connection
        * has been closed by the database, it's removed from the pool
        * and this method is called again recursively.
        */
        synchronized Connection getConnection() {
            Connection con = null;

            while ( (freeConnections.size() > 0) && (con == null) ) {
                // Pick the first Connection in the Vector
                // to get round-robin usage
                con = (Connection) freeConnections.firstElement();
                freeConnections.removeElementAt(0);
                try {
                    if (con.isClosed()) {
                        log.info("Removed bad connection in DBConnectionPool.");
                        con = null; // to make the while loop to continue
                    }
                } catch (SQLException e) {
                    con = null; // to make the while loop to continue
                }
            } // while

            if (con == null) {// cannot get any connection from the pool
                if (maxConn == 0 || checkedOut < maxConn) {// maxConn = 0 means unlimited connections
                    con = newConnection();
                }
            }
            if (con != null) {
                checkedOut++;
            }
            return con;
        }

        /**
        * Checks out a connection from the pool. If no free connection
        * is available, a new connection is created unless the max
        * number of connections has been reached. If a free connection
        * has been closed by the database, it's removed from the pool
        * and this method is called again recursively.
        * <P>
        * If no connection is available and the max number has been
        * reached, this method waits the specified time for one to be
        * checked in.
        *
        * @param timeout The timeout value in milliseconds
        */
        /**
        * Note that this method is not synchronized since it relies on the getConnection(void) method
        * I also believe that this method SHOULD NOT synchronized because I use #sleep() method
        * @todo: check if we should synchronize this method and use wait instead of sleep ???
        */
        Connection getConnection(long timeout) {
            long startTime = System.currentTimeMillis();
            Connection con;
            while ((con = getConnection()) == null) {
                long elapsedTime = System.currentTimeMillis() - startTime;
                if (elapsedTime >= timeout) {
                    // Timeout has expired
                    return null;
                }

                long timeToWait = timeout - elapsedTime;
                if (timeToWait > TIME_BETWEEN_RETRIES) timeToWait = TIME_BETWEEN_RETRIES;// we dont want to wait for more than TIME_BETWEEN_RETRIES second each time
                try {
                    Thread.sleep(timeToWait);
                } catch (InterruptedException e) {}
            }
            return con;
        }

        /**
        * Closes all available connections.
        * @return true if the pool is empty and balance
        *        false if the pool has returned some connection to outside
        */
        synchronized boolean release() {
            boolean retValue = true;
            Enumeration allConnections = freeConnections.elements();
            while (allConnections.hasMoreElements()) {
                Connection con = (Connection) allConnections.nextElement();
                try {
                    con.close();
                } catch (SQLException e) {
                    log.error("Cannot close connection in DBConnectionPool.");
                }
            }
            freeConnections.removeAllElements();
            if (checkedOut != 0) {
                retValue = false;
                log.warn("DBConnectionManager: the built-in connection pool is not balanced.");
            }
            checkedOut = 0;
            return retValue;
        }

        /**
        * Creates a new connection, using a userid and password
        * if specified.
        * @todo: check if this method need synchronized
        */
        private Connection newConnection() {
            Connection con = null;
            try {
                if (user == null) {
                    con = DriverManager.getConnection(URL);
                } else {
                    con = DriverManager.getConnection(URL, user, password);
                }
                con.setAutoCommit(true);//thread 804 by trulore
            } catch (SQLException e) {
                log.error("Cannot create a new connection in DBConnectionPool. URL = " + URL, e);
                return null;
            }
            return con;
        }
    }
}
  • DBOptions.java
/*
* $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/db/DBOptions.java,v 1.24 2005/01/26 04:54:28 minhnn Exp $
* $Author: minhnn $
* $Revision: 1.24 $
* $Date: 2005/01/26 04:54:28 $
*
* ====================================================================
*
* Copyright (C) 2002-2005 by MyVietnam.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* All copyright notices regarding MyVietnam and MyVietnam CoreLib
* MUST remain intact in the scripts and source code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
* Correspondence and Marketing Questions can be sent to:
* info@MyVietnam.net
*
* @author: Minh Nguyen  minhnn@MyVietnam.net
* @author: Mai  Nguyen  mai.nh@MyVietnam.net
*/
package net.myvietnam.mvncore.db;

import java.io.File;

import net.myvietnam.mvncore.configuration.DOM4JConfiguration;
import net.myvietnam.mvncore.util.FileUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class DBOptions {

    private static Log log = LogFactory.getLog(DBOptions.class);

    private static final String OPTION_FILE_NAME = "mvncore.xml";

    //default values
    boolean useDatasource  = false;
    // MUST NOT refer to DBUtils, or we will get an infinite recurse
    int databaseType        = 0; //DATABASE_UNKNOWN

    // if useDatasource = true
    String datasourceName  = "";

    // if useDatasource = false
    String driverClassName  = "org.gjt.mm.mysql.Driver";
    String databaseURL      = "jdbc:mysql://localhost/mvnforum?useUnicode=true&characterEncoding=utf-8";
    String databaseUser    = "root";
    String databasePassword = "";
    int maxConnection      = 20;
    int maxTimeToWait      = 2000;// 2 seconds
    int minutesBetweenRefresh = 30;// 30 minutes

    private DBOptions() {
        try {
            String strPathName = FileUtil.getServletClassesPath();
            String configFilename = strPathName + OPTION_FILE_NAME;
            DOM4JConfiguration conf = new DOM4JConfiguration(new File(configFilename));


            useDatasource = conf.getBoolean("dboptions.use_datasource", false);
            databaseType = conf.getInt("dboptions.database_type", 0);

            if (useDatasource) {
                datasourceName = conf.getString("dboptions.datasource_name");
            } else {
                driverClassName = conf.getString("dboptions.driver_class_name", driverClassName);
                databaseURL = conf.getString("dboptions.database_url", databaseURL);
                databaseUser = conf.getString("dboptions.database_user", databaseUser);
                databasePassword = conf.getString("dboptions.database_password",databasePassword);

                maxConnection = conf.getInt("dboptions.max_connection", maxConnection);
                maxTimeToWait = conf.getInt("dboptions.max_time_to_wait", maxTimeToWait);

                minutesBetweenRefresh = conf.getInt("dboptions.minutes_between_refresh", minutesBetweenRefresh);
                if (minutesBetweenRefresh < 1) {
                    minutesBetweenRefresh = 1; //min is 1 minute
                }
            }
        } catch (Exception e) {
            String message = "net.myvietnam.mvncore.db.DBOptions: Can't read the configuration file: '" + OPTION_FILE_NAME + "'. Make sure the file is in your CLASSPATH";
            log.error(message, e);
        }
    } //constructor
}
  • DBUtils.java
/*
* $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/db/DBUtils.java,v 1.21 2005/01/28 07:49:45 minhnn Exp $
* $Author: minhnn $
* $Revision: 1.21 $
* $Date: 2005/01/28 07:49:45 $
*
* ====================================================================
*
* Copyright (C) 2002-2005 by MyVietnam.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* All copyright notices regarding MyVietnam and MyVietnam CoreLib
* MUST remain intact in the scripts and source code.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*
* Correspondence and Marketing Questions can be sent to:
* info@MyVietnam.net
*
* @author: Minh Nguyen  minhnn@MyVietnam.net
* @author: Mai  Nguyen  mai.nh@MyVietnam.net
*/
package net.myvietnam.mvncore.db;

import java.sql.*;

import javax.sql.DataSource;

import net.myvietnam.mvncore.MVNCoreConfig;
import net.myvietnam.mvncore.MVNCoreInfo;
import net.myvietnam.mvncore.util.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* A  database utility class to handle all the database stuffs
* in the MyVietnam framework
*/
public final class DBUtils {

    private static Log log = LogFactory.getLog(DBUtils.class);

    public static final int DATABASE_UNKNOWN    = 0;
    public static final int DATABASE_GENERAL    = 1;
    public static final int DATABASE_NOSCROLL    = 2;

    public static final int DATABASE_ORACLE      = 10;
    public static final int DATABASE_SQLSERVER  = 11;
    public static final int DATABASE_DB2        = 12;
    public static final int DATABASE_SYBASE      = 13;
    public static final int DATABASE_IMFORMIX    = 14;
    public static final int DATABASE_MYSQL      = 15;
    public static final int DATABASE_POSTGRESQL  = 16;
    public static final int DATABASE_HSQLDB      = 17;
    public static final int DATABASE_ACCESS      = 18;
    public static final int DATABASE_SAPDB      = 19;
    public static final int DATABASE_INTERBASE  = 20;
    public static final int DATABASE_FIREBIRD    = 21;

    private static int databaseType = DATABASE_UNKNOWN;

    private static boolean useDatasource = false;

    private static int maxTimeToWait = 2000;// 2 seconds

    private static int minutesBetweenRefresh = 30;// 30 minutes

    private static DBConnectionManager connectionManager = null;

    private static DataSource dataSource = null;

    private static long lastGetConnectionTime = 0;

    private static long lastCloseAllConnectionsTime = 0;

    // static init of the class
    static {
        //DBOptions option = new DBOptions();

        //databaseType = option.databaseType;
        databaseType = MVNCoreConfig.getDatabaseType();
        if (databaseType != DATABASE_UNKNOWN) {
            log.info("Set DATABASE_TYPE = " + databaseType);
        }
        useDatasource = MVNCoreConfig.isUseDataSource();
        if (useDatasource) {
            String dataSourceName = "";
            try {
                javax.naming.Context context = new javax.naming.InitialContext();
                // sample data source = java:comp/env/jdbc/MysqlDataSource
                dataSourceName = MVNCoreConfig.getDataSourceName();
                dataSource = (DataSource) context.lookup(dataSourceName);
                log.info("DBUtils : use datasource = " + dataSourceName);
            } catch (javax.naming.NamingException e) {
                //log.error("Cannot get DataSource: datasource name = " + option.datasourceName, e);
                log.error("Cannot get DataSource: datasource name = " + dataSourceName, e);
            }
        } else {
            //maxTimeToWait = option.maxTimeToWait;
            maxTimeToWait = MVNCoreConfig.getMaxTimeToWait();
            //minutesBetweenRefresh = option.minutesBetweenRefresh;
            minutesBetweenRefresh = MVNCoreConfig.getMinutesBetweenRefresh();
            connectionManager = DBConnectionManager.getInstance(true/* a new method*/);
            log.info("DBUtils : use built-in DBConnectionManager (MAX_TIME_TO_WAIT = " + maxTimeToWait + ", MINUTES_BETWEEN_REFRESH = " + minutesBetweenRefresh + ")");
        }
        log.info("DBUtils inited. Detailed info: " + MVNCoreInfo.getProductVersion() + " (Build: " + MVNCoreInfo.getProductReleaseDate() + ")");
    }

    private DBUtils() {// so cannot new an instance
    }

    /**
    * Use this method to get the database type. This method will automatically
    * detect the database type. You could override this value by modifying
    * the value in mvncore_db_DBOptions.properties
    * @return : the database type
    */
    public static int getDatabaseType() {
        if (databaseType == DATABASE_UNKNOWN) {
            Connection connection = null;
            try {
                connection = DBUtils.getConnection();
                DatabaseMetaData dbmd = connection.getMetaData();
                String databaseName = dbmd.getDatabaseProductName().toLowerCase();
                if (databaseName.indexOf("oracle") != -1) {
                    databaseType = DATABASE_ORACLE;
                } else if (databaseName.indexOf("sql server") != -1) {
                    databaseType = DATABASE_SQLSERVER;
                } else if (databaseName.indexOf("mysql") != -1) {// "MySQL"
                    databaseType = DATABASE_MYSQL;
                } else if (databaseName.indexOf("postgresql") != -1) {
                    databaseType = DATABASE_POSTGRESQL;
                } else if (databaseName.indexOf("hsql") != -1) {
                    databaseType = DATABASE_HSQLDB;
                } else if (databaseName.indexOf("sap") != -1) {// "SAP DB"
                    databaseType = DATABASE_SAPDB;
                } else if (databaseName.indexOf("firebird") != -1) {//"firebird"
                    databaseType = DATABASE_FIREBIRD;
                } else {
                    databaseType = DATABASE_GENERAL;
                }
                log.info("Auto detect DATABASE_TYPE = " + databaseType + " (" + getDatabaseTypeName(databaseType) + ")");
            } catch (Exception ex) {
                log.error("Error when running getDatabaseType", ex);
            } finally {
                DBUtils.closeConnection(connection);
            }
        }
        return databaseType;
    }

    public static String getDatabaseTypeName(int databaseType) {
        String databaseTypeName = "Cannot find databaseType = " + databaseType;
        switch (databaseType) {
        case DATABASE_UNKNOWN:
            databaseTypeName = "DATABASE_UNKNOWN";
            break;
        case DATABASE_GENERAL:
            databaseTypeName = "DATABASE_GENERAL";
            break;
        case DATABASE_NOSCROLL:
            databaseTypeName = "DATABASE_NOSCROLL";
            break;
        case DATABASE_ORACLE:
            databaseTypeName = "DATABASE_ORACLE";
            break;
        case DATABASE_SQLSERVER:
            databaseTypeName = "DATABASE_SQLSERVER";
            break;
        case DATABASE_DB2:
            databaseTypeName = "DATABASE_DB2";
            break;
        case DATABASE_SYBASE:
            databaseTypeName = "DATABASE_SYBASE";
            break;
        case DATABASE_IMFORMIX:
            databaseTypeName = "DATABASE_IMFORMIX";
            break;
        case DATABASE_MYSQL:
            databaseTypeName = "DATABASE_MYSQL";
            break;
        case DATABASE_POSTGRESQL:
            databaseTypeName = "DATABASE_POSTGRESQL";
            break;
        case DATABASE_HSQLDB:
            databaseTypeName = "DATABASE_HSQLDB";
            break;
        case DATABASE_ACCESS:
            databaseTypeName = "DATABASE_ACCESS";
            break;
        case DATABASE_SAPDB:
            databaseTypeName = "DATABASE_SAPDB";
            break;
        case DATABASE_INTERBASE:
            databaseTypeName = "DATABASE_INTERBASE";
            break;
        case DATABASE_FIREBIRD:
            databaseTypeName = "DATABASE_FIREBIRD";
            break;
        }
        return databaseTypeName;
    }

    /**
    * Get a connection from the connection pool. The returned connection
    * must be closed by calling DBUtils.closeConnection()
    * @return : a new connection from the pool if succeed
    * @throws SQLException : if cannot get a connection from the pool
    */
    public static Connection getConnection() throws SQLException {

        long now = System.currentTimeMillis();
        lastGetConnectionTime = now;
        // now check if we have not close all connections to refresh
        // after MINUTES_BETWEEN_REFRESH minutes, then will do it now
        if (now - lastCloseAllConnectionsTime > DateUtil.MINUTE * minutesBetweenRefresh) {
            boolean isBalance = closeAllConnections();
            if (isBalance == false) {
                try {
                    // wait for the checked-out connections to be returned and closed
                    Thread.sleep(2000);
                    log.debug("DBUtils: sleep 2 seconds for checked-out connections to returned and closed.");
                } catch (Exception ex) { }
            }
        }

        Connection conection = null;

        if (useDatasource) {
            if (dataSource != null) {
                conection = dataSource.getConnection();
            }
        } else {
            if (connectionManager != null) {
                conection = connectionManager.getConnection(maxTimeToWait);
            } else {
                log.fatal("Assertion: DBUtils.connectionManager == null");
            }
        }

        if (conection == null) {
            throw new SQLException("DBUtils: Cannot get connection from Connection Pool.");
        }
        return conection;
    }

    /**
    * Close all the connections that currently in the pool
    * This method could be used to refresh the database connection
    * @return true if the pool is empty and balance
    *        false if the pool has returned some connection to outside
    */
    public static boolean closeAllConnections() {
        log.debug("DBUtils.closeAllConnections is called.");
        boolean retValue = true;// balance (default)
        lastCloseAllConnectionsTime = System.currentTimeMillis();
        if (useDatasource) {
            if (dataSource != null) {
                // do nothing here now
            }
        } else {
            if (connectionManager != null) {
                retValue = connectionManager.release();
            } else {
                log.fatal("Assertion: DBUtils.connectionManager == null");
            }
        }
        return retValue;
    }

    /**
    * Use this method to return the connection to the connection pool
    * Do not use this method to close connection that is not from
    * the connection pool
    * @param connection : the connection that needs to be returned to the pool
    */
    public static void closeConnection(Connection connection) {
        if (connection == null) return;

        if (useDatasource) {
            try {
                connection.close();
            } catch (SQLException e) {
                log.error("DBUtils: Cannot close connection.", e);
            }
        } else {
            connectionManager.freeConnection(connection);
        }
    }

    /**
    * Use this method to reset the MaxRows and FetchSize of the Statement
    * to the default values
    * @param statement : the statement that needs to be reseted
    */
    public static void resetStatement(Statement statement) {
        if (statement != null) {
            try {
                statement.setMaxRows(0); //reset to the default value
            } catch (SQLException e) {
                log.error("DBUtils: Cannot reset statement MaxRows.", e);
            }

            try {
                statement.setFetchSize(0); //reset to the default value
            } catch (SQLException sqle) {
                //do nothing, postgreSQL doesnt support this method
            }
        }
    }

    /**
    * Use this method to close the Statement
    * @param statement : the statement that needs to be closed
    */
    public static void closeStatement(Statement statement) {
        try {
            if (statement != null) statement.close();
        } catch (SQLException e) {
            log.error("DBUtils: Cannot close statement.", e);
        }
    }

    /**
    * Use this method to close the ResultSet
    * @param rs : the resultset that needs to be closed
    */
    public static void closeResultSet(ResultSet rs) {
        try {
            if (rs != null) rs.close();
        } catch (SQLException e) {
            log.error("DBUtils: Cannot close resultset.", e);
        }
    }

    /*
    public static void main(String[] args) {
        //DBUtils DBUtils1 = new DBUtils();
        //log.info("i = " + dataSource1);
    }*/
}

역시 오래된 소스입니다.

https://hermeslog.tistory.com/398?category=302342 

 

[오픈소스] DBConnectionManager.java

import java.io.*; import java.sql.*; import java.util.*; import java.util.Date; public class DBConnectionManager { static private DBConnectionManager instance; // The single instance private Vector..

hermeslog.tistory.com

 

728x90