简体   繁体   中英

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. I have a Java class that needs to have its delete() method called.

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. 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() . Sadly, it doesn't exist, and we have to rely on the GC implementation to take care of memory management.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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