C3P0在多线程下的maxPoolSize配置
ETL工具完畢的差點兒相同了。今天遇到一個問題。就是給C3P0配置了maxPoolSize為10。目的是想讓整個應(yīng)用同一時候獲得的最大的Connection個數(shù)為10,可是在測試應(yīng)用的這一部分之后,發(fā)現(xiàn)PostgreSQL端的鏈接遠(yuǎn)遠(yuǎn)超過10個。由于工具是多線程的。所以就想,是不是多線程的問題,查了一下Connection的個數(shù),也確實是10*線程個數(shù)。于是做了一個測試:
將maxPoolSize配置為5。執(zhí)行以下的程序:
ComboPooledDataSource cpds = new ComboPooledDataSource("postgres");for (int i = 0; i < 10; i++) {cpds.getConnection();} ComboPooledDataSource cpds2 = new ComboPooledDataSource("postgres");for (int i = 0; i < 10; i++) {cpds2.getConnection();}maxPoolSize配置為5。一共想要獲取20個鏈接,這時查看PostgreSQL Server端的連接數(shù)為5,正式預(yù)期的結(jié)果。
在執(zhí)行以下的程序:
for (int i = 0; i < 2; i++) {new Thread(new Runnable() {@Overridepublic void run() {ComboPooledDataSource cpds = new ComboPooledDataSource("postgres");for (int i = 0; i < 10; i++) {try {cpds.getConnection();} catch (SQLException e) {e.printStackTrace();}}try {Thread.sleep(100000);} catch (InterruptedException e) {e.printStackTrace();}}}, "Thread" + i).start();}兩個線程,每一個線程想要獲取10個鏈接數(shù),這時查看PostgreSQL Server端的鏈接數(shù),是10個。將i<2改為i<3,在執(zhí)行一次,查看PostgreSQL Server端的連接數(shù)是15。
再進(jìn)行以下的測試:
final ComboPooledDataSource cpds = new ComboPooledDataSource("postgres");for (int i = 0; i < 3; i++) {new Thread(new Runnable() {@Overridepublic void run() {for (int i = 0; i < 10; i++) {try {cpds.getConnection();} catch (SQLException e) {e.printStackTrace();}}try {Thread.sleep(100000);} catch (InterruptedException e) {e.printStackTrace();}}}, "Thread" + i).start();創(chuàng)建3個線程,每一個線程須要10個Connection,這時查看PostgreSQL Server端的連接數(shù)是5。可見,PostgreSQL Server端的鏈接的個數(shù)與client創(chuàng)建的ComboPooledDataSource實例的個數(shù)成正比。C3P0配置文件里配置的內(nèi)容都是針對一個ComboPooledDataSource實例的限制。
結(jié)論:
底層的原因大概是由于C3P0不是為多線程設(shè)計的,在底層JDBC也不是線程安全的。
詳細(xì)的原因,有機會在詳細(xì)分析。
一個應(yīng)用中一般一個數(shù)據(jù)源僅僅用一個ComboPooledDataSource對象,也就是一個ComboPooledDataSource實例。
轉(zhuǎn)載于:https://www.cnblogs.com/mengfanrong/p/5129613.html
總結(jié)
以上是生活随笔為你收集整理的C3P0在多线程下的maxPoolSize配置的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: InstallShield limite
- 下一篇: 工作内外网同时连接方案