CLIプロセスのスレッドプールでの私の他の回答から適応
これにより、引き出し可能な接続プールが作成されます。これにより、接続がスレッドごとに上下するのを防ぐことができます。ただし、これは、どのスレッドがどの接続を使用するかが問題でない場合にのみ機能します。問題がある場合は、このコードを調整するか、他の誰かが提案した ThreadLocal を使用して、スレッドが終了したときにフックする必要があります。
新しい作業項目がキューに入れられると、スレッドは接続プールに接続を要求します。利用できない場合は、新しいものを作成します。利用可能な場合、接続がまだ有効であることを確認し、そのオブジェクトを返します。作業項目が終了すると、それを接続プールに戻すことができます。
public class StackOverflow_10037379_jdk6 {
private static Logger sLogger = Logger.getLogger(StackOverflow_10372827_jdk6.class.getName());
public static class ConnectionPoolableObjectFactory extends BasePoolableObjectFactory<Connection> {
public ConnectionPoolableObjectFactory() {
}
@Override
public Connection makeObject() throws Exception {
Connection connection = // createConnection
return connection;
}
@Override
public boolean validateObject(Connection connection) {
return connection.isValid();
}
@Override
public void destroyObject(Connection connection) throws Exception {
connection.close();
}
@Override
public void passivateObject(Connection connection) throws Exception {
}
}
public static class WorkItem implements Runnable {
private ObjectPool<Connection> mPool;
private String mWork;
public CLIWorkItem(ObjectPool<Connection> pool, String work) {
mPool = pool;
mWork = work;
}
@Override
public void run() {
Connection connection = null;
try {
connection = mPool.borrowObject();
// do stuff with connection
} catch (Exception ex) {
sLogger.log(Level.SEVERE, null, ex);
} finally {
if (connection != null) {
try {
// Seriously.. so many exceptions.
mPool.returnObject(connection );
} catch (Exception ex) {
sLogger.log(Level.SEVERE, null, ex);
}
}
}
}
}
public static void main(String[] args) throws Exception {
// Change the 5 to 20 in your case.
ObjectPool<Connection> pool =
new GenericObjectPool<Connection>(
new ConnectionPoolableObjectFactory(), 5);
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(100, true);
ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 20, 1, TimeUnit.HOURS, queue);
// print some stuff out.
executor.execute(new WorkItem(pool, "Message 1\r\n"));
executor.execute(new WorkItem(pool, "Message 2\r\n"));
executor.execute(new WorkItem(pool, "Message 3\r\n"));
executor.execute(new WorkItem(pool, "Message 4\r\n"));
executor.execute(new WorkItem(pool, "Message 5\r\n"));
executor.execute(new WorkItem(pool, "Message 6\r\n"));
executor.execute(new WorkItem(pool, "Message 7\r\n"));
executor.execute(new WorkItem(pool, "Message 8\r\n"));
executor.execute(new WorkItem(pool, "Message 9\r\n"));
executor.execute(new WorkItem(pool, "Message 10\r\n"));
executor.execute(new WorkItem(pool, "Message 11\r\n"));
executor.shutdown();
executor.awaitTermination(4000, TimeUnit.HOURS);
pool.close();
}
}