I have developed a Java web application which connects to MySQL Database using JDBC connector and making the pool of 2 connections. The application is deployed on tomcat server.
Mmy question is, does this code impacts to MySQL available connections if I deploy the application multiple times and the code doesn't have any line to close the available connection when I am shutting down the tomcat? Does tomcat take care of closing the connections when getting restarted?
Connection Util:
import javax.sql.DataSource;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
public class MySQLConnectionPool {
public static DataSource setUpPool(){
GenericObjectPool gPool = null;
String dbName = "DBName";
String userName = "Username";
String password = "Password";
String hostname = "Host";
String port = "Port";
try {
Class.forName("com.mysql.jdbc.Driver");
// Creates an Instance of GenericObjectPool That Holds Our Pool of Connections Object!
gPool = new GenericObjectPool();
gPool.setMaxActive(2);
// Creates a ConnectionFactory Object Which Will Be Use by the Pool to Create the Connection Object!
ConnectionFactory cf = new DriverManagerConnectionFactory("jdbc:mysql://" + hostname + ":" + port + "/" + dbName, userName, password);
// Creates a PoolableConnectionFactory That Will Wraps the Connection Object Created by the ConnectionFactory to Add Object Pooling Functionality!
PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, gPool, null, null, false, true);
}catch (Exception e) {
// TODO: handle exception
System.out.println("Error: "+e.toString());
}
return new PoolingDataSource(gPool);
}
}
DAO:
@Override
public ArrayList<User> getUserDetails(String environment, String MySQLQuery) {
// TODO Auto-generated method stub
ArrayList<User> users = new ArrayList<User>();
Connection connObj = null;
Statement stmt = null;
ResultSet result = null;
try {
DataSource dataSource = MySQLConnectionPool.setUpPool();
// Performing Database Operation!
System.out.println("\n=====Making A New Connection Object For Db Transaction=====\n");
connObj = dataSource.getConnection();
stmt = connObj.createStatement();
result = stmt.executeQuery(MySQLQuery);
while(result.next()) {
//Some code here
}
System.out.println("\n=====Releasing Connection Object To Pool=====\n");
} catch(Exception sqlException) {
} finally {
try {
// Closing ResultSet Object
if(result != null) {
result.close();
}
// Closing Statement Object
if(stmt != null) {
stmt.close();
}
// Closing Connection Object
if(connObj != null) {
connObj.close();
}
} catch(Exception sqlException) {
}
}
return users;
}