简体   繁体   English

如何使对象有资格从对象内部进行垃圾回收?

[英]How to make an object eligible for garbage collection from inside the object?

I'm looking for a way to delete an object in Java, make it eligible for GC.我正在寻找一种在 Java 中删除对象的方法,使其有资格进行 GC。 I have a Java class that needs to have its delete() method called.我有一个需要调用其 delete() 方法的 Java 类。

public class SomeObj {

    // some implementation stuff
    //...

    void delete() {
        //remove yourself from some lists in the program
        //...

        this = null; // <- this line is illegal

        //delete this; <- if I was in C++, I could do this
    }
}

How should I do this?我该怎么做? Apparently, I'm going to have to refactor my code because this smells like bad design.显然,我将不得不重构我的代码,因为这闻起来像是糟糕的设计。

For better or worse, Java is a language that runs in a garbage-collecting environment.不管好坏,Java 是一种运行在垃圾收集环境中的语言。 An object has some kind of existence in an application so longer as it is reachable via references.一个对象在应用程序中存在某种形式,因为它可以通过引用访问。 Once it is no longer reachable -- when no other object holds a reference to it -- it is "deleted" so far as the application is concerned.一旦它不再可达——当没有其他对象持有对它的引用时——就应用程序而言,它被“删除”。

That the object still has some after-life in the heap is a matter for the garbage collector, not the application.对象在堆中仍然有一些死后生命是垃圾收集器的问题,而不是应用程序的问题。 An application that depends on being able to control the existence of objects to which there are no references is broken in some logical sense.依赖于能够控制没有引用的对象的存在的应用程序在某种逻辑意义上被破坏了。

The usual, semi-legitimate reason for wanting to nudge an unreferenced object out of the heap for good is to conserve heap space.想要将未引用的对象从堆中移出的通常的、半合法的原因是为了节省堆空间。 There have been many, many occasions when I've known when an object is really finished with better than the garbage collector ever could.有很多很多时候,我知道一个对象何时真的比垃圾收集器更好地完成了。 Objects that store temporary results with method scope are a good example.使用方法范围存储临时结果的对象就是一个很好的例子。 I'm primarily a C and C++ developer, and I really want a method on java.lang.Object called ImDoneWithYouNow() .我主要是一名 C 和 C++ 开发人员,我真的想要一个名为ImDoneWithYouNow() java.lang.Object方法。 Sadly, it doesn't exist, and we have to rely on the GC implementation to take care of memory management.遗憾的是,它不存在,我们必须依靠 GC 实现来处理内存管理。

You don't need (and really shouldn't have) a "destructor".你不需要(也不应该有)“析构函数”。 Once no other object references the object in question, it becomes eligible for garbage collection, and will be removed by the garbage collector when it sees fit.一旦没有其他对象引用有问题的对象,它就有资格进行垃圾收集,并在垃圾收集器认为合适时将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM