我正在嘗試爲Executor服務使用連接池。Java執行器服務連接池
當連接池配置爲initialSize = 3,maxToal = 5,maxIdle = 5時,我遇到了一些問題。
我需要每分鐘處理10個服務。但它每分鐘只選擇5項服務。
如果我爲每分鐘配置INITIALSIZE = 3,maxToal = 10,了maxidle = 10,則其採摘10個服務..
我是新來的多線程和連接。以下是我的代碼片段。請提供建議。
public class TestScheduledExecutorService {
public static void main (String a[]) {
ScheduledExecutorService service = null;
try {
TestObject runnableBatch = new TestObject() {
public void run() {
testMethod();
}
};
service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(runnableBatch, 0, 30, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestObject implements Runnable{
public void testMethod (int inc) {
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
service.submit(new TestService());
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
}
}
public class TestService implements Callable{
Connection conn = null;
public void process(Connection conn) {
try {
if (conn != null) {
System.out.println("Thread & Connection pool conn : "+Thread.currentThread() + " :: " +conn);
// service process here
} else {
System.out.println("Connection pool conn is null : ");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Override
public Object call() throws Exception {
ConnectionPoolTest cp = ConnectionPoolTest.getInstance();
BasicDataSource bds = cp.getBasicDataSource();
conn = bds.getConnection();
System.out.println(" call() "); **// it prints only 5 times for every minute eventhough total services are 10**
process(conn);
return null;
}
}
public class ConnectionPoolTest {
private static ConnectionPoolTest dataSource = new ConnectionPoolTest();
private static BasicDataSource basicDataSource = null;
private ConnectionPoolTest() {
}
public static ConnectionPoolTest getInstance() {
if (dataSource == null)
dataSource = new ConnectionPoolTest();
return dataSource;
}
public BasicDataSource getBasicDataSource() throws Exception {
try {
basicDataSource = new BasicDataSource();
basicDataSource.setInitialSize(3);
basicDataSource.setMaxTotal(10);
basicDataSource.setMaxIdle(10);
} catch (Exception e) {
throw e;
}
return basicDataSource;
}
}
你的「單身人士」已經壞了。你不應該每次都像現在一樣創建一個新的'BasicDataSource'。 – Kayaman
謝謝卡亞曼。你能告訴我這個解決方案嗎? – DEADEND
沒有簡單的解決方案。你的代碼在很多方面都是錯誤的,我建議讀一些關於連接池和執行程序的文章(教程,其他stackoverflow文章等)。目前,你正以完全錯誤的方式使用它們。 – Kayaman