2012-11-06 42 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或文件句柄將關閉資源。你應該在你獲得它的方法範圍內的最後一個塊中做到這一點。