Search code examples
javaobjectgarbage-collectiongarbage

How can I delete a specific object?


How can I manually delete a specific object before the garbage collector would ever collect it ? For example I want to delete requestToken object. How can I do that ?


Solution

  • The short answer is that you can't, and that you don't need to. The GC will reclaim the memory when it needs to ... and there is no reason to interfere with that.

    The only situation I can think of for needing to delete an object sooner is when the object contains information that needs to be erased ... for information security reasons. (The classic example is when you are processing a password provided by the user and you are worried that it might leak via a code dump or something) In that case, you need to implement a method on your object for erasing the object's fields by overwriting them. But this requires careful design; e.g. to make sure that you find and erase all traces of the information.

    It is also sometimes necessary to "help" the GC a bit to avoid potential memory leaks. A classic example of this is the ArrayList class, which uses a Java array to represent the list content. The array is often larger than the list's logical size, and the elements of the array could contain pointers to objects that have been removed from the list. The ArrayList class deals with this by assigning null to these elements.

    Note that neither of these examples involve actually deleting objects. In both cases, the problem / issue is addressed another way.


    It is also worth noting that calling System.gc() is usually a bad idea:

    • It is not guaranteed to do anything at all.
    • In most situations, it won't do anything that wouldn't happen anyway.
    • In most situations, it is inefficient. The JVM is in a better position than application code to know the ergonomically most efficient time to run the GC. (Read this for a first-principles explanation of the ergonomics.)

    The only cases where running the GC in production code is advisable are when you are trying to manage GC pauses, and you know that a pause is acceptable at a particular point in time. (For example, when you are changing levels in an interactive game ... )