改编自我在CLI Processes 的 ThreadPool 的其他回答
这将创建一个连接池,您可以从中提取。这将防止每个线程的连接数上升和下降。但是,这仅在哪个线程使用哪个连接无关紧要时才有效。如果它确实重要,您必须调整此代码或使用其他人建议的 ThreadLocal 并在 Thread 死亡时挂钩。
当一个新的工作项排队时,线程会向连接池请求一个连接。如果一个不可用,它将创建一个新的。如果有一个可用,它将验证连接是否仍然有效,然后返回该对象。当工作项完成后,它可以将其返回到连接池。
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();
}
}