2012-11-06 41 views
3

我想弄清楚当我的对象被取消时可以关闭与服务的连接的最佳方式。关闭连接的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)关闭某些东西的“正确”方式是什么?如果我能避免它,我不想将关闭问题推广到程序的下一层。

感谢有关如何最好地做到这一点的任何提示!

回答

5

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

具体来说,你没有得到任何保证为:

  1. 当JVM将实现对象是弱可及;
  2. 当弱引用将被清除;
  3. 当JVM将通过将它排入参考队列来通知您这一事实。稀缺资源的
+0

确实 - 这意味着不要这样做?这个连接不是一个可以被限制在一个函数或类中的连接。它实际上是一个由“something”类封装的共享资源。 Soooo不这样做? – rybit

+0

无论你遇到什么问题,使用弱引用都不会解决它,但会引入另一个问题。 –

+0

这就是我害怕的:/ – rybit

1

垃圾收集,就像SQL ResultSetStatementConnection或文件句柄将关闭资源。你应该在你获得它的方法范围内的最后一个块中做到这一点。