代码之家  ›  专栏  ›  技术社区  ›  nullPointer

DBCP连接池

  •  1
  • nullPointer  · 技术社区  · 7 年前

    请问下面的代码是否正确地使用了连接池(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可能被多个派生线程使用。 这个代码有什么我没有看到的潜在问题吗?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Ivan    7 年前

    DatabaseUtility.getDataSource 第一次。最后可能会有多个数据源实例。请阅读以下链接以了解线程安全的惰性单例初始化: https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples

        2
  •  1
  •   Karol Dowbecki    7 年前

    如果你换成 HikariCP 池连接验证设置将自动处理。看看池中的几个陷阱,例如:

    推荐文章