用于关闭连接的Java弱引用

问题描述 投票:4回答:2

当我的对象被描述时,我试图找出关闭服务连接的最佳方法。

我有这样的事情:

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)关闭某些东西的“正确”方法是什么?如果可以避免,我不想将关闭问题提升到程序的下一层。

java weak-references
2个回答
5
投票

是的:在Java中,将任何资源的管理与内存管理相结合是一种弊端。除了内存管理之外的一切都必须明确地完成。 Java 7引入了一个名为“自动资源管理”的有用的新构造,它有助于所涉及的样板。

具体而言,您无法保证:

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

1
投票

垃圾收集稀缺资源,如SQL ResultSetStatementConnection或文件句柄将不会关闭资源。您应该在获取它的方法范围内的finally块中执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.