Tomcat JNDI连接池docs - 随机连接已关闭异常 [英] Tomcat JNDI Connection Pool docs - Random Connection Closed Exceptions

查看:766
本文介绍了Tomcat JNDI连接池docs - 随机连接已关闭异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Tomcat文档中找到了这一点,这里

I found this in the Tomcat documentation here

我不明白的是为什么他们关闭所有的JDBC对象两次 - 一次在try {}块和一次在finally {}块。为什么不在finally {}子句中关闭它们一次?

What I don't understand is why they close all the JDBC objects twice - once in the try{} block and once in the finally{} block. Why not just close them once in the finally{} clause?

这是相关的文档:

These can occur when one request gets a db connection from the connection pool and closes it twice. When using a connection pool, closing the connection just returns it to the pool for reuse by another request, it doesn't close the connection. And Tomcat uses multiple threads to handle concurrent requests. Here is an example of the sequence of events which could cause this error in Tomcat:

  Request 1 running in Thread 1 gets a db connection.

  Request 1 closes the db connection.

  The JVM switches the running thread to Thread 2

  Request 2 running in Thread 2 gets a db connection
  (the same db connection just closed by Request 1).

  The JVM switches the running thread back to Thread 1

  Request 1 closes the db connection a second time in a finally block.

  The JVM switches the running thread back to Thread 2

  Request 2 Thread 2 tries to use the db connection but fails
  because Request 1 closed it.

Here is an example of properly written code to use a db connection obtained from a connection pool:

  Connection conn = null;
  Statement stmt = null;  // Or PreparedStatement if needed
  ResultSet rs = null;
  try {
    conn = ... get connection from connection pool ...
    stmt = conn.createStatement("select ...");
    rs = stmt.executeQuery();
    ... iterate through the result set ...
    rs.close();
    rs = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null;  // Make sure we don't close it twice
  } catch (SQLException e) {
    ... deal with errors ...
  } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rs != null) {
      try { rs.close(); } catch (SQLException e) { ; }
      rs = null;
    }
    if (stmt != null) {
      try { stmt.close(); } catch (SQLException e) { ; }
      stmt = null;
    }
    if (conn != null) {
      try { conn.close(); } catch (SQLException e) { ; }
      conn = null;
    }
  }


推荐答案

你可以使用Spring-JDBC并忘记所有这些复杂情况(Spring-JDBC会自动为你处理)

Or you can using Spring-JDBC and forget about all this complications (Spring-JDBC will deal with this automatically for you)

这篇关于Tomcat JNDI连接池docs - 随机连接已关闭异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆