ryb*_*bit 4 java weak-references
当我的对象被描述时,我试图找出关闭服务连接的最佳方法.
我有这样的事情:
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 ()
}
Run Code Online (Sandbox Code Playgroud)
这样我可以实例化这样的东西:
somefunction () {
something = new something ()
}
Run Code Online (Sandbox Code Playgroud)
当方法返回(并且是descoped/gc'd)时,它将正确关闭连接.
问题:(1)这真的很棒吗?!?!(2)它是否有效(测试是......正在进行中......)?(3)关闭某些东西的"正确"方法是什么?如果可以避免,我不想将关闭问题提升到程序的下一层.
是的:在Java中,将任何资源的管理与内存管理相结合是一种弊端.除了内存管理之外的一切都必须明确地完成.Java 7引入了一个名为"自动资源管理"的有用的新构造,它有助于所涉及的样板.
具体而言,您无法保证: