gpt4 book ai didi

java - 如何通过连接池实现多线程

转载 作者:太空宇宙 更新时间:2023-11-04 12:13:39 25 4
gpt4 key购买 nike

我有 Calc Runner 类。在这个类中,基于没有数量的公司执行的 4 个方法意味着这样。

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

在此方法中,从 DBStatic util 类获取连接。就像这样`

 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 程序

最佳答案

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

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);

关于java - 如何通过连接池实现多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com