我想弄清楚当我的对象被取消时可以关闭与服务的连接的最佳方式。关闭连接的Java弱引用
我有这样的事情:
class something {
public final LongConnection lc;
public something() {
lc = new LongConnection();
lc.initConnection();
new Thread (new Runnable() {
public void run() {
ReferenceQueue<LongConnection> rq = new ReferenceQueue<LongConnection>();
WeakReference<LongConnection> wr = new WeakReference<LongConnection> (lc, rq);
// now it should start listening for the object to be added to the queue
while (true) {
Reference<? extends LongConnection> ref = rq.remove();
if (rq != null) {
rq.get().shutdown();
break;
}
}
// will fall through and die!
}
}).start()
}
这样我可以实例化是这样的:
somefunction() {
something = new something()
}
,并在方法返回时(并descoped/gc'd),它会正确关闭连接。
问题:(1)这真的太棒了!!?! (2)它会工作(测试是......正在进行中......)? (3)关闭某些东西的“正确”方式是什么?如果我能避免它,我不想将关闭问题推广到程序的下一层。
感谢有关如何最好地做到这一点的任何提示!
确实 - 这意味着不要这样做?这个连接不是一个可以被限制在一个函数或类中的连接。它实际上是一个由“something”类封装的共享资源。 Soooo不这样做? – rybit
无论你遇到什么问题,使用弱引用都不会解决它,但会引入另一个问题。 –
这就是我害怕的:/ – rybit