简体   繁体   English

多线程Java程序中的连接池

[英]Connection Pooling in Multi Threaded Java Program

I have a java process which is multi threaded using ExecutorService (15 threads). 我有一个使用ExecutorService(15个线程)多线程的Java进程。 Each thread calls stored procedure to insert data to table, my connection to be pooled across 15 threads so that I could see multiple commits on the table at the same time, but i only see one connection established for one active thread even through 15 threads are ready and waiting. 每个线程都调用存储过程以将数据插入表中,我的连接被池化到15个线程中,这样我就可以同时看到表上的多个提交,但是我只看到为一个活动线程建立了一个连接,即使有15个线程也是如此。准备好并等待。

Tried using the below code to establish connection and pooled across all threads 尝试使用以下代码建立连接并在所有线程之间进行池化

Class.forName(DB_DRIVER);

DataSource oracleDataSource = new DriverManagerDataSource(DB_CONNECTION, DB_USER,DB_PASSWORD);

ObjectPool objectPool = new GenericObjectPool();

DataSourceConnectionFactory datasourceConnectionFactory = new DataSourceConnectionFactory(oracleDataSource);

PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(datasourceConnectionFactory, objectPool, null, null, false, true);

objectPool.setFactory(poolableConnectionFactory);

PoolingDataSource datasource = new PoolingDataSource(objectPool); 

but it didn't work still. 但它仍然无法正常工作。 Still my threads are using only one connection and other threads are waiting for the active one to complete. 我的线程仍然只使用一个连接,而其他线程正在等待活动的连接完成。

You could encapsulate the connection to the DB in a class and create a pool of objects of this class yourself. 您可以将与数据库的连接封装在一个类中,然后自己创建一个此类的对象池。

Example

class Connection {
//  your DB connection specific stuff
public void open() {
//  open connection
}

public void close() {
// close connection
}

public void isOpen() {
//  is the connection being opened by any thread already
}
}

Once you have this, create a thread safe method which will return the next available connection object to any requesting thread. 一旦有了这个,就创建一个线程安全的方法,该方法将下一个可用的连接对象返回到任何发出请求的线程。

class ConnectionController {
public Connection getConnection() {
//  return the next available connection object by checking which 
//connection object is not open by checking return value of isOpen
}
}

Make sure you close the connection once you are done! 完成后,请确保关闭连接! Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM