java - DBCP 连接池

标签 java jdbc connection-pooling dbcp

请问下面的代码是否可以正确使用连接池 (DBCP)?

我提供 BasicDataSource 的实用程序类如下(几乎与 apache 示例相同)

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;
    }

然后我将上面的用作:

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;
    }
}

MyClass 类可能被多个生成的线程使用。 我没有看到此代码的任何潜在问题?

非常感谢

最佳答案

如果多个不同的线程将首次调用 DatabaseUtility.getDataSource,您可能会遇到问题。您最终可能会得到多个数据源实例。阅读此链接以了解线程安全的惰性单例初始化:https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples

关于java - DBCP 连接池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538877/

相关文章:

java - 跨 Hibernate session 和普通 jdbc 的单个事务

mysql - Spring Boot : Communications link failure after some hours of inactivity with Hibernate, JDBC 和 MySQL

database - 使用 C3P0 时如何最好地关闭连接并避免非事件 session ?

java - scala 重载构造函数中的逻辑

java - 如何在这段代码中只使用一个数组实例?

java - 将嵌入式 Jetty 服务器从版本 6 迁移到版本 7

java - 如何将 jdbc-realm 配置为 jBoss jbpm

java - 支持 boolean 查询的内存数据结构

java - Spring Boot 连接池配置最佳实践

sql-server - ADO.NET SQLServer : How to prevent closed connection from holding S-DB lock?