关于java:Glassfish不重用JDBC连接

Glassfish does not reuse JDBC Connections

我在glassfish Web服务器上使用JDBC连接池。我通过以下语句注入数据源:

1
2
@Resource(lookup="database")
DataSource db;

我用来加载数据的代码看起来像这样:

1
2
3
4
5
6
7
8
9
10
11
12
public ArrayList<Stuff> loadStuff()throws SQLException{
    PreparedStatement ps = db.getConnection().prepareStatement("Select * from stufftable");
    ResultSet rs = ps.executeQuery();
    ArrayList<Stuff> stuffs= new ArrayList<Stuff>();
    if(rs.next()){
        Stuff stuff = new Stuff();
        stuff.setString1(rs.getString("string1"));
        stuff.setString1(rs.getString("string1"));
        stuffs.add(stuff );
    }
    return stuffs;
}

出于某种原因,glassfish不会重用数据库连接,因此我很快就用光了它们。
迟早我总是会收到此错误:Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections.

据我所知,在玻璃鱼上池化的概念是:我不应该在使用连接后关闭连接,因此在需要时其他某些东西可以重用该连接。当不再有连接需求时,Glassfish会自行关闭连接。

为什么我的程序每次都打开一个新连接?完成后,我必须对连接做些什么吗?


您仍然需要呼叫Connection.close()。您的池将管理您的连接,因此不会真正关闭它们,但是如果您未在代码中"关闭"它们,它们将不会返回到池中。

编辑:或者,使用try-with-resources:
https://stackoverflow.com/a/8066594/212224


1
2
3
4
5
6
7
8
Connection con = db.getConnection();
try {
    PreparedStatement ps = con.prepareStatement("Select * from stufftable");
    ...
} finally {
    // this returns the connection to the pool
    con.close();
}