I'm new to web apps but I'm using a database connection in my webapp and I had a question. I found some good info online about connection pooling and I'm trying to implement it. http://java.sun.com/developer/onlineTraining/Programming/JDCBook/conpool.html I used the classes from here and modified it a little bit so that I could associate my own database object with a connection. I understand how it saves resources by putting connections in a pool instead of making a new one each time.
Here's my session listener class. The static part creates the connection pool and sets everything up. Then when a session is created a new connection is returned from the pool unless there's an existing free connection, in which case, that one is returned. Then when the session is destroyed, the connection is returned to the pool. My question is, when is a session destroyed? If I close the browser, it doesn't call session destroyed, so when in fact would the session be destroyed? I'm worried that the connection would never go back into the pool.
public class SessionListener implements HttpSessionListener
{
static
{
try
{
Logger.init();
Logger.log("Initializing Database");
new JDCConnectionDriver(Resources.VARS.getString("driver"),Resources.VARS.getString("string"),Resources.VARS.getString("user"),Resources.VARS.getString("password"));
}
catch(Exception e){}
}
public void sessionCreated(HttpSessionEvent event)
{
Logger.log("New session created");
HttpSession session = event.getSession();
JDCConnection conn = null;
try
{
conn = (JDCConnection) DriverManager.getConnection("jdbc:jdc:jdcpool");
DatabaseContainer db = conn.getDB();
Logger.log("Connection added to session");
session.setAttribute("db", db);
}
catch (SQLException e)
{
Logger.log(e.getMessage());
}
}
public void sessionDestroyed(HttpSessionEvent event)
{
HttpSession session = event.getSession();
DatabaseContainer db = (DatabaseContainer)session.getAttribute("db");
if (db != null)
{
try
{
Logger.log("Connection returned to pool");
db.getConnection().close();
session.removeAttribute("db");
}
catch (SQLException e)
{
Logger.log(e.getMessage());
}
}
Logger.log("Session destroyed");
}
}