gpt4 book ai didi

用于关闭连接的 Java 弱引用

转载 作者:搜寻专家 更新时间:2023-11-01 02:13:10 24 4
gpt4 key购买 nike

当我的对象被取消作用域时,我正在尝试找出关闭与服务的连接的最佳方法。

我有这样的东西:

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 ()
}

并且当方法返回(并且被取消作用域/gc'd)时,它将正确关闭连接。

问题:(1) 这真的很糟糕吗?!?!(2) 它会起作用吗(测试……正在进行中……)?(3) 关闭某物的“正确”方法是什么?如果可以避免,我不想将关机问题提升到程序的下一层。

最佳答案

是的:在 Java 中,将任何资源的管理与内存管理耦合在一起是不当行为。除了内存管理之外的所有事情都必须显式完成。 Java 7 引入了一个有用的新结构,称为“自动资源管理”,有助于处理所涉及的样板文件。

具体而言,您无法获得以下方面的任何保证:

  1. JVM 何时会意识到对象是弱可达的;
  2. 弱引用何时被清除;
  3. JVM 何时会通过将其排入您的引用队列来通知您该事实。

关于用于关闭连接的 Java 弱引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com