I am trying to get the jdbc connection using proxool connection pool in a Web application. Below code describes the same :
public static Connection getConnection(String key, boolean useConnectionPool, String poolName) {
Connection connection = null;
String alias = "DBCP" + poolName + "_" + key;
String driverClass = "com.mysql.jdbc.Driver";
checkAndLoadProps();
String driverUrl = "jdbc:mysql://" + props.getProperty(key + "_DBMS_URL") + "/" + props.getProperty(key + "_DEF_SCHEMA") + "?autoReconnect=true&useUnicode=true&characterEncoding=utf8&jdbcCompliantTruncation=false&rewriteBatchedStatement=true";
String connectionPoolUrl = "proxool." + alias + ":" + driverClass + ":" + driverUrl;
try {
if (useConnectionPool) {
info.remove("user");
String user = props.getProperty(key + "_CLIENT");
info.setProperty("user", user);
info.remove("password");
String password = props.getProperty(key + "_CLIENT_PASS");
info.setProperty("password", password);
String host = props.getProperty(key + "_DBMS_URL");
synchronized (poolName) {
connection = DriverManager.getConnection(connectionPoolUrl, info);
}
}
if (connection != null) {
return connection;
} else {
System.out.println("DB Connection Not Established");
}
} catch (Exception ex) {
System.out.println("DB Connection Not Established::" + ex.getMessage());
ex.printStackTrace();
}
return null;
}
What happens is as soon as I start my server, more than 1 threads try to access this code parallely and it throws concurrent modification exception.
I understand it can be fixed by providing class level lock to the synchronized block. But it will severely affect the performance.
Any better solution to this?