Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark an object for garbage collection by the GC (Garbage Collector)?

In Java, is there a way to mark an object for garbage collection by the GC, during its next clean up cycle?

I've heard that setting an object to null no longer works.

like image 990
monksy Avatar asked Mar 16 '11 20:03

monksy


1 Answers

No, you can't. What would you expect to happen if another variable had a reference to it?

Note that you can't set an object to null - you can only set a variable to null. If another variable still has a reference to the object, it will still not be eligible for garbage collection.

If you think you need to do this, that probably means you're misinterpreting your data - or that you may have a leak somewhere in your code (e.g. a list which you only ever add entries to, referenced by a static variable - those entries will never be eligible for garbage collection while the classloader is alive).

Each JVM has its own GC, but in Hotspot an object will be garbage collected next time the GC runs over the generation that object currently "lives" in (assuming it doesn't have a finalizer, which complicates things). If the object is in a "young" generation, that will probably happen quite soon - if it's in an "old" generation it may well take longer.

You may want to see the Java 6 GC tuning documentation for more information, although of course things have moved on since then for OpenJDK 7 etc.

like image 97
Jon Skeet Avatar answered Sep 19 '22 18:09

Jon Skeet