I am wondering whether you would consider it a good practice to remove references (setting them to null
) to objects in order to help the Java Garbage Collector.
For instance, let's say you have a class with two fields, one of them being very memory-consuming. If you know you only need it for a particular processing, you can null it right after to help the GC.
Assume I really need those two to be fields, and not only internal variables, so heavyObject1
cannot be out of scope at the end of the method.
Would you do this as a general practice?
public class TestClass {
public static Object heavyObject1;
public static Object object2;
private static void action() {
object2 = doSomething(heavyObject1);
heavyObject1 = null; //is this good?
}
}
If your application's object creation rate is very high, then to keep up with it, the garbage collection rate will also be very high. A high garbage collection rate will increase the GC pause time as well. Thus, optimizing the application to create fewer objects is THE EFFECTIVE strategy to reduce long GC pauses.
This should never be used in production code.There is harm in calling the garbage collector explicitly. Calling the GC at the wrong time wastes CPU cycles. You (the programmer) do not have enough information to determine when the right time is ... but the JVM does.
Garbage Collection occurs if at least one of multiple conditions is satisfied. These conditions are given as follows: If the system has low physical memory, then garbage collection is necessary. If the memory allocated to various objects in the heap memory exceeds a pre-set threshold, then garbage collection occurs.
Impacts On PerformanceGC is slow, mostly because it needs to pause program execution to collect garbage.
Usually it isn't needed.
It's a good idea in the following specific circumstance:
However if you find yourself in this situation I suspect you have a design smell anyway: why does the internal object have such a different scope / lifetime from the enclosing object? This makes me suspicious, because usually when you build up an object graph with composition you expect the composed objects to have similar lifetimes.
In most of the cases, you dont need to set the object to null to be garbage collected.If you decalre the object in proper scope(method level,instance level or class level), the object will be unreachable immediately after its use and will be eligible for garbage collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With