I have a Java-JSF Web Application on GlassFish, in which I want to use connection pooling. Therefore I created an application
scoped bean that serves with Connection
instances for other beans:
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class DatabaseBean {
private DataSource myDataSource;
public DatabaseBean() {
try {
Context ctx = new InitialContext();
ecwinsDataSource = (DataSource) ctx.lookup("jdbc/myDataSource");
} catch (NamingException ex) {
ex.printStackTrace();
}
}
public Connection getConnection() throws ClassNotFoundException, SQLException, InstantiationException, IllegalAccessException {
Connection connection = myDataSource.getConnection();
System.out.println("Succesfully connected: " + connection);
//Sample: Succesfully connected: com.sun.gjc.spi.jdbc40.ConnectionHolder40@7fb213a5
return connection;
}
}
This way the connection pool gets filled very fast; after a few navigation through 'db-related' views, the application stops with the following:
RAR5117 : Failed to obtain/create connection from connection pool [ mysql_ecwins_ecwinsPool ]. Reason : In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections. RAR5114 : Error allocating connection : [Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections.] java.sql.SQLException: Error in allocating a connection. Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate more connections. at com.sun.gjc.spi.base.DataSource.getConnection(DataSource.java:115) at beans.DatabaseBean.getConnection(DatabaseBean.java:24)
I'm closing connections and other resources in every method. The application runs all OK with standalone connections.
What am I doing wrong? Any tips or advice would be appreciated.
EDIT
I looked into the way I am closing resources and it came out I wasn't very thorough. Now I'm closing them this way:
private void close(Connection connection, ResultSet rs, Statement stmt) {
try {
if (rs != null) {
rs.close();
}
} catch (Exception ex) {
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception ex) {
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (Exception ex) {
}
}
}
}
I don't get the error anymore! YAY, thanks!:)