Could I please ask whether the below code would be correctly using connection pooling (DBCP) ?
My utility class providing the BasicDataSource is as below (almost identical to the apache example)
public class DatabaseUtility {
private static BasicDataSource dataSource;
public static BasicDataSource getDataSource(Properties prop) {
if (dataSource == null)
{
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:oracle:thin:@"+ prop.getProperty("db") + ":" + prop.getProperty("dbPort") + "/" +
prop.getProperty("dbService"));
ds.setUsername(prop.getProperty("dbUser"));
ds.setPassword(prop.getProperty("dbPassword"));
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
dataSource = ds;
}
return dataSource;
}
I am then using the above as :
public class MyClass {
public static boolean isNew(Properties prop, String label) {
Connection connection = null;
PreparedStatement ps = null;
try {
BasicDataSource dataSource = DatabaseUtility.getDataSource(prop);
connection = dataSource.getConnection();
ps = connection.prepareStatement("Select * from my_table where LABEL = CAST( ? AS CHAR(35))");
ps.setString(1, label);
if (ps.executeQuery().isBeforeFirst()) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ps != null)
ps.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
System.out.println("Error while closing resource :");
e.printStackTrace();
}
}
return true;
}
}
Class MyClass could be possibly be used by multiple spawned threads. Any potential issues with this codes that I am not seeing ?
Many thanks
You can face problems if several different threads will call
DatabaseUtility.getDataSource
for the first time. You may end up with several instances of your datasource. Read this link for thread-safe lazy singleton initialization: https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples