java - 如何修复此 Try-With-Resources block 中出现的 "SQLServerException: The connection is closed."问题?

标签 java jdbc try-with-resources

我正在对 DBMS 进行性能测试。我必须为我的硕士论文手动完成它。我必须有一定数量的线程,每个线程打开自己的 JDBC 连接到数据库(连接池不是一个选项)并提交相同数量的相同事务(每个线程执行相同的工作)。我将连接作为 try-with-resources block 中的资源打开。连接应保持打开状态,直到 try-with-resources 范围结束,但有时会,有时不会。

try (Connection conn = getConn();
    PreparedStatement simpleSelectStmt = conn
                         .prepareStatement(tcInstance.getQueryMap().get("SimpleSelect").getSimpleSelect())) {

        setConnIsolation(conn);

        long startTime = System.nanoTime();
        singleThread.execute(new Runnable() {

            @Override
            public void run() {

                for (int j = 0; j < tcInstance.getnT(); j++) {
                    try {
                        conn.setAutoCommit(false);
                        simpleSelectStmt.execute();
                        conn.commit();
                    } catch (Exception e) {
                        error++;
                        if (detectDeadlock(e.getMessage())) {
                            deadlock++;
                            System.out.println("Deadlock detected!");
                        } else {
                            e.printStackTrace();
                        }

                        try {
                            if (conn != null) {
                                conn.rollback();
                            }
                        } catch (SQLException e1) {
                            System.out.println("There was an error in rolling back the transaction.");
                            e1.printStackTrace();
                        }

                    }

                    if (j != (tcInstance.getnT() - 1)) {
                        try {
                            Thread.sleep(t);// ms
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }

                measureCPUusage(Thread.currentThread().getId());
                singleThread.shutdown();

        });

        long endTime = System.nanoTime();
        ....doing some other measurements....

    } catch (Exception e) {
        System.err.println("Error");
    }

这是用于获取 jdbc 连接的 getConn() 方法:

private Connection getConn() throws SQLException {
    return DriverManager.getConnection(tcInstance.getJDBCurl(), tcInstance.getUser(), tcInstance.getPassword());
}

我希望通过整个 try-with-resources block 打开连接,但是在 conn.setAutoCommit(false);conn.rollback 行上存在“连接已关闭”异常();

最佳答案

您的代码流程简而言之似乎是这样的:

try (Connection conn = getConn()) {
    setConnIsolation(conn);

    // Posted from Thread-1
    singleThread.execute(new Runnable() {

        @Override
        public void run() {

        // Thread-2 accesses conn created on Thread-1
        // use conn here..
    });

   // ....doing some other work....

} catch (Exception e) {
    System.err.println("Error");
}

//Conn is released

当可运行对象开始工作时,其相应的线程可能正在使用已释放的 conn。这是因为,发布线程在发布可运行对象之后,从 Try-With-Resources block 中出来,并且作为其中的一部分,Conn 被释放。

解决方案: 将 Conn 移出 Try-With-Resources block 。

关于java - 如何修复此 Try-With-Resources block 中出现的 "SQLServerException: The connection is closed."问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56253024/

相关文章:

java - 如何修复方法 setLatestEventInfo(Context, String, String, PendingIntent) 未定义类型通知

java - 无法进入jsp文件中的if语句

java - try-with-resource 中的 close() 异常

Java 使用 Clip 和 Try - with - resources block 导致没有声音

java - 在 try-with-resource 中手动关闭

java - 有没有办法使用 HK2 将实例注入(inject)集合中?

java - 如何在运行时刷新 JPanel?

java - 如何抛出 Spring @Valid "exception"?

java - ResultSet 在 while next() 循环中间关闭异常

java - 访问 PostgreSQL 数据库的 JDBC 驱动程序有哪些替代方案