我想弄清楚當我的對象被取消時可以關閉與服務的連接的最佳方式。關閉連接的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