c3p0获取连接Connection后的Close()---释疑

时间:2022-09-18 19:51:37
  • 论题:
    • java c3p0获取连接Connnection 之后, 调用 con.close( ) 是否真的关闭了物理连接 ?
  • 简答:
    • c3p0采用连接池, 目的就是提前预置一定数量的连接, 在使用时候重复利用这些连接, 所以, con.close() 之后, 物理连接当然是被放回了连接池, 而没有真正的关闭 .
    • c3p0中的池连接(指:Connection) 是实现了PooledConnection接口的, PooledConnection为连接池管理提供钩子 (hook) 的对象, 它会在connnection被操作时接收到消息, 从而对该操作加以干涉,将Connection连接放回连接池.
  • 疑问:
    • 一些童鞋经过试验,发现如下问题,于是发出路上疑问, con.close()真的关闭了连接吗...
    •  public class MyTest {
      /**
      * 开启了20个线程,返回的hashcode,如下:没有重复的
      *1730967171 1122742512 156948859 1210106945 1217158489
      *1868341939 1595154849 1873764403 1937202425 1629470861
      */
      public static void main(String[] args) {
      for (int i = 0; i < 10; i++) {
      new Thread(new Runnable() {
      @Override
      public void run() { Connection con = JDBCUtil.getConnection();
      System.out.println(con.hashCode());
      // ....
      con.close();
      } catch (SQLException e) {
      e.printStackTrace();
      }
      }
      }).start();
      }
      }
      }
      public class JDBCUtil {
      /**
      * <!-- 最大空闲时间设置为0 , 即永不过期 -->
      * <property name="maxIdleTime">0</property>
      * <!-- 最多有多少个连接 -->
      * <property name="maxPoolSize">5</property>
      * <!-- 最少几个连接 -->
      * <property name="minPoolSize">2</property>
      */
      private static Connection conn;
      private static ComboPooledDataSource ds = new ComboPooledDataSource(); public static Connection getConnection() {
      try {
      conn = ds.getConnection();
      } catch (SQLException e) {
      e.printStackTrace();
      }
      return conn;
      }
      }
    • c3p0源码跟踪 [ps : 水平有限,以下未解释java事件注册相关原理 ]

    •  abstract class AbstractPoolBackedDataSource
      extends PoolBackedDataSourceBase
      implements PooledDataSource{
      //..... // dataSource.getConnection()所调用的就是该方法
      //implementation of javax.sql.DataSource
      public Connection getConnection() throws SQLException{ PooledConnection pc =
      getPoolManager(). // 返回 C3P0PooledConnectionPoolManager
      getPool(). // 返回 C3P0PooledConnectionPool
      checkoutPooledConnection(); // 返回PooledConnection
      return pc.getConnection();
      } //.....
      } class C3P0PooledConnectionPool{
      // ....
      public PooledConnection checkoutPooledConnection() throws SQLException{
      //System.err.println(this + " -- CHECKOUT");
      try
      {
      PooledConnection pc = (PooledConnection) this.checkoutAndMarkConnectionInUse();
      pc.addConnectionEventListener( cl );
      return pc;
      }
      catch (TimeoutException e)
      { throw SqlUtils.toSQLException("An attempt by a client to checkout a Connection has timed out.", e); }
      catch (CannotAcquireResourceException e)
      { throw SqlUtils.toSQLException("Connections could not be acquired from the underlying database!", "08001", e); }
      catch (Exception e)
      { throw SqlUtils.toSQLException(e); }
      } private Object checkoutAndMarkConnectionInUse() throws TimeoutException, CannotAcquireResourceException, ResourcePoolException, InterruptedException
      {
      Object out = null;
      boolean success = false;
      while (! success)
      {
      try
      {
      out = rp.checkoutResource( checkoutTimeout );
      if (out instanceof AbstractC3P0PooledConnection)
      {
      // cast should succeed, because effectiveStatementCache implies c3p0 pooled Connections
      AbstractC3P0PooledConnection acpc = (AbstractC3P0PooledConnection) out;
      /*
      *以下在获取物理连接的时候,PooledcConnection中注册的事件监听器会收到消息
      *无论每次对connection的何种操作,PooledConnection都会收到来自驱动的消息,
      *其中的钩子(hook)对象就会完成对Connection的回收
      */
      Connection physicalConnection = acpc.getPhysicalConnection();
      success = tryMarkPhysicalConnectionInUse(physicalConnection);
      }
      else
      success = true; //we don't pool statements from non-c3p0 PooledConnections
      }
      finally
      {
      try { if (!success && out != null) rp.checkinResource( out );}
      catch (Exception e) { logger.log(MLevel.WARNING, "Failed to check in a Connection that was unusable due to pending Statement closes.", e); }
      }
      }
      return out;
      }
      //.... }
  • 综述:
    • 当应用程序关闭连接时,它调用 Connection 方法 close。完成连接池时,连接池管理器将得到通知;因为它曾使用 ConnectionPool 方法 addConnectionEventListener 作为 ConnectionEventListener 对象注册它自身。连接池管理器释放到 PooledConnection 对象的句柄,并将 PooledConnection 对象返回到连接池,以便再次使用。因此,当应用程序关闭其连接时,基础物理连接会被回收而不是被关闭。
    • 知识水平有限,难免错误,模糊, 请多批评指正,谢谢.