我有一个"连接池处理程序"在它的类中有一个"连接处理程序"的数组列表。我想知道是否可以使用"连接处理程序"当他们自己关闭连接时将自己从列表中移除,如果是这样的话?
public class ConnectionHandlerPool
{
private static final ArrayList<ConnectionThread> POOL = new ArrayList<ConnectionThread>;
<code to get stuff out of pool>
连接线程类
public class ConnectionHandlerThread
{
<stuff that creates the connection>
<stuff that if exceptions occur i.e. a stream or socket closes it needs to close all the connections and remove from pool>
<that way of removing it from arraylist in the class above it>
答案 0 :(得分:1)
实现这一目标的最简单方法并不需要复杂的侦听器设计甚至接口。注意:以下代码未考虑所有其他所需逻辑(检出,确保连接无法检出两次等)。
public class ConnectionHandlerPool {
private static final List<ConnectionThread> pool = new ArrayList<ConnectionThread>();
// When new threads are created, they get a reference to the pool they're in
private void addConnection() {
pool.add(new ConnectionThread(pool));
}
private void disconnect(ConnectionThread ct) {
pool.remove(ct);
}
}
public class ConnectionHandlerThread {
private final ConnectionHandlerPool pool;
public ConnectionHandlerThread(ConnectionHandlerPool pool) {
this.pool = pool;
}
private void destroy() {
pool.disconnect(this);
}
}
答案 1 :(得分:0)
经过一些修补和与一些技术伙伴交谈后,我已经解决了。