2016-09-22 77 views
1

我有Calc Runner类。在这个类中执行的4个方法没有公司数量的意思是这样的。如何实现连接池Multi_threading

 for(long companyId : companies){ 
method1(); 
method2(); 
method3(); 
method4(); 
} 

在这种方法正从DBStatic UTIL class.Like这 `

try { 
      synchronized (LOCK_OBJCT) { 
       if (_conn == null || _conn.isClosed()) { 
        Class.forName(DB_DRIVER); 
        logger.debug("Connecting to: " + DB_URL + "; as: " + DB_USERID); 
        _conn = DriverManager.getConnection(DB_URL, DB_USERID, DB_PASSWORD); 
        _conn.setAutoCommit(false); 
       } 
       else { 
        logger.debug("Connected to: " + DB_URL + "; as: " + DB_USERID); 
       } 
      } 
     } catch(ClassNotFoundException ce) { 
      logger.error("Error when obtaining JDBC driver.Exiting...", ce); 
      System.exit(1); 
     } catch(SQLException e) { 
      logger.error("Error when obtaining insight db conn: " + DB_URL + "; as: " + DB_USERID + " Exiting..." , e); 
      System.exit(1); 
     } 

     return _conn; 
    }` 

我我们实施了多线程与ExcutiveService有4个线程池的连接。所有的方法都在线程中执行。 知道连接池的问题多线程无法正常工作。如何实现连接池的JDBC程序用于此多线程

+0

我你实际上是使用'Java的ee'那么服务器管理这一切都为你 - 它只是需要一些配置。不需要重新创建这个特定的轮子 –

回答

0

您应该创建连接池并指定连接限制。然后你就可以实现连接池

PooledConnectionDataSource ds = new PooledConnectionDataSource(); 
ds.setDescription("Oracle Data Source"); 
// Refer to a previously registered pooled data source to access 
// a ConnectionPoolDataSource object 
ds.setDataSourceName("jdbc/ConnectOracle"); 
// The pool manager will be initiated with 5 physical connections 
ds.setInitialPoolSize(5); 
// The pool maintenance thread will make sure that there are 5 
// physical connections available 
ds.setMinPoolSize(5); 
// The pool maintenance thread will check that there are no more 
// than 10 physical connections available 
ds.setMaxPoolSize(10); 
// The pool maintenance thread will wake up and check the pool 
// every 20 seconds 
ds.setPropertyCycle(20); 
// The pool maintenance thread will remove physical connections 
// that are inactive for more than 300 seconds 
ds.setMaxIdleTime(300); 
// Set tracing off since we choose not to see output listing 
// of activities on a connection 
ds.setTracing(false); 
+0

在多线程环境中关闭连接时,我们得到像connect这样的异常已经是closed.we使用Jdbc3PoolingDataSource –