使用ReferenceQueue和WeakReference [英] Using ReferenceQueue and WeakReference

查看:169
本文介绍了使用ReferenceQueue和WeakReference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在不再被其他线程引用时正确关闭Closeable对象。

I want to properly close Closeable object when it's no longer referenced by other threads.

我写了一些小测试,但是在对象入队后get方法返回null ,即poll方法返回没有指示对象的正确Object。

I wrote some small test, but after object is enqueued the get method return null, i.e. the poll method returns proper Object which has no referent.

  public static void main(String[] args)
  {
   ReferenceQueue<Closeable> reaped = new ReferenceQueue<Closeable>();
   Closeable s = <SOME CLOSEABLE IMPL>;
   WeakReference<Closeable> ws = new WeakReference<Closeable>(s, reaped);
   s = null;

   System.gc();
   Closeable ro = (Closeable)reaped.poll().get();
   ro.close();
  }

提前致谢。
任何帮助将不胜感激。

Thanks in advance. Any help will be appreciated.

推荐答案

首先,如果它只是关闭,请使用幻影
接下来,从引用队列中, poll()并不能保证您将获得引用。并且你永远不会得到实际的对象(指示对象)。

First, if it is only about closing, use PhantomReference. Next, from the reference queue, poll() does not guarantee that you will get the reference back. and you will never get the actual object (referent) back.

如果你想确保你的可关闭 s关闭你必须自己跟踪它们,然后在 Map< Reference<?> ;, Closeable> 中说。然后,当您 poll()您的引用队列时,您最终将获得 ref 然后您必须使用它来获取来自地图的可关闭

If you want to make sure your Closeables are closed you have to keep track of them yourself lets say in a Map<Reference<?>, Closeable>. Then when you poll() your reference queue, you will eventually get the ref then you have to use it to get the Closeable from the map.

   class MyThing {
      Closeable c;
   }

   Map<Reference<MyThing>, Closeable> m = new HashMap();
   ReferenceQueue<MyThing> reaped = new ReferenceQueue<MyThing>();

   MyThing mt = new MyThing();
   mt.c = new MyClosable();

   Reference<MyThing> pref = new PhantomReference<MyThing>(mt, reaped);
   m.put(pref, mt.c);

   mt = null;


   System.gc();
   Reference<MyThing> rf = reaped.poll();
   while (rf != null) {
     m.get(rf).close(); 
     rf = reaped.poll();
   }

注意 如果你没有真正的理由这样做,或者你不明白你在做什么,不要做这种事。

Note If you don't have a real reason to do this or if you do not understand what are you really doing, DO NOT do this kind of thing.

你可以关闭你的中的文件和BTW如果是关于文件,套接字等,它们将被关闭(它们已经实现 finalize()

You can close your files in finally and BTW if it is about files, sockets, etc, they are closed for you (they already implement finalize()

这篇关于使用ReferenceQueue和WeakReference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆