本文介绍了等待特定对象的垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 跟踪正在等待删除的文件,并删除它们当关联标记对象被垃圾回收器回收时。 可以在 FileCleaningTracker object。 现在我只是好奇我怎么能自己做到这一点?当垃圾收集器回收对象时,我的代码如何检测?解析方案 根据源代码它使用 PhantomReference 类。根据文档: PhantomReference 构造函数接受两个参数: q 参数是 ReferenceQueue 类的一个实例。 PhantomReference 将被添加到 ReferenceQueue 中,当它是指涉变成幽灵可达。发生这种情况时,可以使用 poll()或 remove()来检索 PhantomReference ) ReferenceQueue class。 例如: T objectToWatch = ...; ReferenceQueue< T> referenceQueue = new ReferenceQueue< T>(); new PhantomReference< T>(objectToWatch,referenceQueue); //稍后,可能在另一个线程中... 参考< ;?延伸T> nextReference = referenceQueue.remove(); //收拾起来! 注意: PhantomReference 具有名为 SoftReference 和 WeakReference ,这也可能是有用的。这些关系记录在 java.lang.ref包文档。 I was just digging around in the commons-io library and found this:Keeps track of files awaiting deletion, and deletes them whenan associated marker object is reclaimed by the garbage collector.This can be found in the documentation for the FileCleaningTracker object.Now I am just curious how I can do this by myself? How can my code detect when an object is reclaimed by the garbage collector? 解决方案 According to the source code, it uses the PhantomReference class. According to the documentation:The PhantomReference constructor accepts two arguments:The q argument is an instance of the ReferenceQueue class. The PhantomReference will be added to this ReferenceQueue when it's referent becomes phantom reachable. When this happens, you can retrieve the PhantomReference by using the poll() or remove() methods of the ReferenceQueue class.For example:T objectToWatch = ...;ReferenceQueue<T> referenceQueue = new ReferenceQueue<T>();new PhantomReference<T>(objectToWatch, referenceQueue);// Later on, probably in another thread...Reference<? extends T> nextReference = referenceQueue.remove();// Tidy up!Note: PhantomReference has sibling classes named SoftReference and WeakReference that may also be of use. The relationship between these are documented in the java.lang.ref package documentation. 这篇关于等待特定对象的垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 02:43