Glassfish关闭JDBC连接

时间:2015-06-12 11:06:18

标签: java jdbc glassfish

我是 Glassfish Java EE 的新手,我尝试使用 glassfish作为服务器开发项目。我遇到的问题是sometiems glassfish部署项目所需的时间太长,因为它正在关闭JDBC Connections ,这需要太长时间。

SEVERE:   Closing JDBC Connection 0
SEVERE:   Closing JDBC Connection 1
SEVERE:   Closing JDBC Connection 2
SEVERE:   Closing JDBC Connection 3
SEVERE:   Closing JDBC Connection 4
...........
SEVERE:   Closing JDBC Connection 19

我不知道问题是来自glassfish服务器还是来自我的代码..我在使用它们后关闭连接..

你能帮我找出问题的来源,我该如何解决?

我将添加更多信息。

我正在使用 GlassFish Server 4.1 Java EE 7 Web。

对于连接,我有以下类:

public class PooledConnection {


private Connection connection = null;
private boolean inuse = false;

// Constructor that takes the passed in JDBC Connection
// and stores it in the connection attribute.
public PooledConnection(Connection value) {
    if (value != null) {
        this.connection = value;
    }
}

// Returns a reference to the JDBC Connection
public Connection getConnection() {
    // get the JDBC Connection
    return this.connection;
}

// Set the status of the PooledConnection.
public void setInUse(boolean value) {
    inuse = value;
}

//Returns the current status of the PooledConnection.
public boolean inUse() {
    return inuse;
}

// Close the real JDBC Connection
public void close() {
    try {
        connection.close();
    } catch (SQLException sqle) {
        System.err.println(sqle.getMessage());
    }
}
}

ConnectionPool类

public class ConnectionPool {

// JDBC Driver Name
private String driver = null;
// URL of database
private String url = null;
// Initial number of connections.
private int size = 0;
// Username
private String username = null;
// Password
private String password = null;
// Vector of JDBC Connections
private ArrayList<PooledConnection> pool = null;
private ArrayList<PooledConnection> poolInUse = null;
private ArrayList<PooledConnection> poolNotInUse  = null;


public ConnectionPool() {
}

// Set the value of the JDBC Driver
public void setDriver(String value) {
    if (value != null) {
        driver = value;
    }
}

// Get the value of the JDBC Driver
public String getDriver() {
    return driver;
}

// Set the URL Pointing to the Datasource
public void setURL(String value) {
    if (value != null) {
        url = value;
    }
}

// Get the URL Pointing to the Datasource
public String getURL() {
    return url;
}

// Set the initial number of connections
public void setSize(int value) {
    if (value > 1) {
        size = value;
    }
}

// Get the initial number of connections
public int getSize() {
    return size;
}

// Set the username
public void setUsername(String value) {
    if (value != null) {
        username = value;
    }
}

// Get the username
public String getUserName() {
    return username;
}

// Set the password
public void setPassword(String value) {
    if (value != null) {
        password = value;
    }
}

// Get the password
public String getPassword() {
    return password;
}

// Creates and returns a connection
private Connection createConnection() throws Exception {
    Connection con = null;
    // Create a Connection
    con = DriverManager.getConnection(url, username, password);
    return con;
}

// Initialize the pool
public synchronized void initializePool() throws Exception {
    // Check our initial values
    if (driver == null) {
        throw new Exception("No Driver Name Specified!");
    }
    if (url == null) {
        throw new Exception("No URL Specified!");
    }
    if (size < 1) {
        throw new Exception("Pool size is less than 1!");
    }
    // Create the Connections
    try {
        // Load the Driver class file

        Class.forName(driver);
        // Create Connections based on the size member
        for (int x = 0; x < size; x++) {
            System.err.println("Opening JDBC Connection " + x);
            Connection con = createConnection();
            if (con != null) {
                // Create a PooledConnection to encapsulate the real JDBC Connection
                PooledConnection pcon = new PooledConnection(con);
                // Add the Connection to the pool
                addConnection(pcon);
            }
        }
    } catch (SQLException sqle) {
        System.err.println(sqle.getMessage());
    } catch (ClassNotFoundException cnfe) {
        System.err.println(cnfe.getMessage());
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
}

// Adds the PooledConnection to the pool
private void addConnection(PooledConnection value) {
    // If the pool is null, create a new vector with the initial size of 
    if(pool == null)
    {
        pool = new ArrayList<PooledConnection>(size);
    }

    pool.add(value);
}

public synchronized void releaseConnection(Connection con)
{
    if(con != null)  
    {
        // find the PooledConnection Object
        for (int x = 0; x < pool.size(); x++) {
            PooledConnection pcon = pool.get(x);
            // Check for correct Connection
            if (pcon.getConnection() == con) {
                System.err.println("Releasing Connection " + x);
                // Set its inuse attribute to false, which
                // releases it for use
                pcon.setInUse(false);
                break;
            }
        }
    }
}

// Find an available connection
public synchronized Connection getConnection() throws Exception {
    PooledConnection pcon = null;
    // find a connection not in use
    for (int x = 0; x < pool.size(); x++) {
        pcon = pool.get(x);
        // Check to see if the Connection is in use
        if (pcon.inUse() == false) {
            // Mark it as in use
            pcon.setInUse(true);
            // return the JDBC Connection stored in the
            // PooledConnection object
            return pcon.getConnection();
        }
    }
    // Could not find a free connection, create and add a new one
    try {
        // Create a new JDBC Connection
        Connection con = createConnection();
        // Create a new PooledConnection, passing it the JDBC Connection
        pcon = new PooledConnection(con);
        // Mark the connection as in use
        pcon.setInUse(true);
        // Add the new PooledConnection object to the pool
        pool.add(pcon);
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    // return the new Connection
    return pcon.getConnection();
}

// When shutting down the pool, you need to first empty it.
public synchronized void emptyPool() {
    // Iterate over the entire pool closing the JDBC Connections.
    for (int x = 0; x < pool.size(); x++) {
        System.err.println("Closing JDBC Connection " + x);
        PooledConnection pcon = pool.get(x);
        // If the PooledConnection is not in use, close it
        if (pcon.inUse() == false) {
            pcon.close();
        } else {
            // If it is still in use, sleep for 30 seconds and force close.
            try {
                java.lang.Thread.sleep(30000);
                pcon.close();
            } catch (InterruptedException ie) {
                System.err.println(ie.getMessage());
            }
        }
    }
}
}

和DBAccessController

public final class DBAccessController {

private Connection connection = null;

public DBAccessController(String url, String userId, String password, boolean typereadonly) {
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
        connection = DriverManager.getConnection(url, userId, password);
        connection.setReadOnly(typereadonly);
    } catch (java.lang.ClassNotFoundException exceptionClassNotFound) {
    } catch (java.lang.InstantiationException instantException) {
    } catch (java.lang.IllegalAccessException illegalAccess) {
    } catch (java.sql.SQLException sqle) {
    }

}

public DBAccessController(Connection con) {

    if (con != null) {
        this.connection = con;
    }

}


public final synchronized ArrayList runSQL(String queryString, List<String> parametrii) {
    try {

        PreparedStatement prepStmt = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
        connection.setAutoCommit(true);
        for (int i = 0; i < parametrii.size(); i++) {
            prepStmt.setString((i + 1), parametrii.get(i));
        }
        ResultSet rs = prepStmt.executeQuery();

        boolean flag = prepStmt.execute();


        ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
        ResultSet keyset = prepStmt.getGeneratedKeys();

        while (keyset != null && keyset.next()) {

            HashMap<String, String> keysHM = new HashMap<>();
            // Retrieve the auto generated key(s).
            int key = keyset.getInt(1);
            keysHM.put("cheia", Integer.toString(key));
            rezultate.add(keysHM);

        }

        if (flag) {
            ResultSet res = prepStmt.getResultSet();
            ResultSetMetaData rsmd = res.getMetaData();
            int numberOfColumns = rsmd.getColumnCount();

            while (res.next()) {

                HashMap<String, String> hm = new HashMap<>();

                    Object o = res.getObject(i);

                    if (o != null) {
                        hm.put(rsmd.getColumnName(i), o.toString());
                    }
                }

                rezultate.add(hm);
            }

            res.close();
            prepStmt.close();
            return rezultate;

        } else {
            prepStmt.close();
            if (keyset != null) {
                return rezultate;
            } else {
                return null;
            }
        }

    } catch (java.sql.SQLException sqle) {
        return null;
    }
}



public final synchronized ArrayList runSQL(String queryString) {
    try {

        PreparedStatement statement = connection.prepareStatement(queryString, PreparedStatement.RETURN_GENERATED_KEYS);
        connection.setAutoCommit(true);
        boolean flag = statement.execute();

        System.out.println("Statement: " + statement + " flag: " + flag);

        ArrayList<HashMap<String, String>> rezultate = new ArrayList<>();
        ResultSet keyset = statement.getGeneratedKeys();

        while (keyset != null && keyset.next()) {

            HashMap<String, String> keysHM = new HashMap<>();
            // Retrieve the auto generated key(s).
            int key = keyset.getInt(1);
            keysHM.put("cheia", Integer.toString(key));
            rezultate.add(keysHM);

            System.out.println("Cheile " + keyset.toString());

        }

        System.out.println("Cheile " + keyset.toString());
        if (flag) {
            ResultSet res = statement.getResultSet();
            ResultSetMetaData rsmd = res.getMetaData();
            int numberOfColumns = rsmd.getColumnCount();

            System.out.println("res: " + res + " rsmd: " + rsmd + " numberOfColumns: " + numberOfColumns);

            while (res.next()) {

                HashMap<String, String> hm = new HashMap<>();
                System.out.println("Res to string " + res.toString());
                for (int i = 1; i <= numberOfColumns; i++) {
                    System.out.println("obiectul " + i + " res.getObject(i) " + res.getObject(i));

                    Object o = res.getObject(i);
                    System.out.println("rsmd.getColumnName(i) " + rsmd.getColumnName(i));

                    if (o != null) {
                        hm.put(rsmd.getColumnName(i), o.toString());
                    }
                }

                rezultate.add(hm);
            }

            res.close();
            statement.close();
            System.out.println("Return rezultate");
            return rezultate;

        } else {
            System.out.println("Return null 1");
            statement.close();
            if (keyset != null) {
                return rezultate;
            } else {
                return null;
            }
        }

    } catch (java.sql.SQLException sqle) {
        System.out.println("Return null 2" + sqle.getMessage());
        return null;
    }
}

public final void stop() {

    try {
        connection.close();
    } catch (java.sql.SQLException e) {
    }
}

}

当我需要使用连接时,我会执行以下操作(例如):

Connection con;
                try {
                    con = cp.getConnection();
                    udao = new UtilizatorDAO(con);
                    con.close();
                    }


                } catch (Exception ex) {
                    Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
                }
                out.close();

0 个答案:

没有答案
相关问题