Does Assigning Objects to Null in Java Impact Garbage Collection

Does assigning objects to null in Java impact garbage collection?

Typically, no.

But like all things: it depends. The GC in Java these days is VERY good and everything should be cleaned up very shortly after it is no longer reachable. This is just after leaving a method for local variables, and when a class instance is no longer referenced for fields.

You only need to explicitly null if you know it would remain referenced otherwise. For example an array which is kept around. You may want to null the individual elements of the array when they are no longer needed.

For example, this code from ArrayList:

public E remove(int index) {
RangeCheck(index);

modCount++;
E oldValue = (E) elementData[index];

int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work

return oldValue;
}

Also, explicitly nulling an object will not cause an object to be collected any sooner than if it just went out of scope naturally as long as no references remain.

Both:

void foo() {
Object o = new Object();
/// do stuff with o
}

and:

void foo() {
Object o = new Object();
/// do stuff with o
o = null;
}

Are functionally equivalent.

Does setting Java objects to null do anything anymore?

It depends a bit on when you were thinking of nulling the reference.

If you have an object chain A->B->C, then once A is not reachable, A, B and C will all be eligible for garbage collection (assuming nothing else is referring to either B or C). There's no need, and never has been any need, to explicitly set references A->B or B->C to null, for example.

Apart from that, most of the time the issue doesn't really arise, because in reality you're dealing with objects in collections. You should generally always be thinking of removing objects from lists, maps etc by calling the appropiate remove() method.

The case where there used to be some advice to set references to null was specifically in a long scope where a memory-intensive object ceased to be used partway through the scope. For example:

{
BigObject obj = ...
doSomethingWith(obj);
obj = null; <-- explicitly set to null
doSomethingElse();
}

The rationale here was that because obj is still in scope, then without the explicit nulling of the reference, it does not become garbage collectable until after the doSomethingElse() method completes. And this is the advice that probably no longer holds on modern JVMs: it turns out that the JIT compiler can work out at what point a given local object reference is no longer used.

Java Garbage Collection: Does setting 'top of stack' to null in pop() method only GC the reference (not object)?

It is worth it to set S[top] to null. The reference to the popped object is returned to the caller who can do anything to that object. When the caller is done with that object, then it no longer needs to be referenced by either the caller or the Stack. As long as no other object references it, then it is eligible for garbage collection.

If the Stack didn't clear that entry, then nothing would make it eligible for garbage collection, because the Stack would continue holding a reference to that object even after it was popped.

In the Stack, the array and any references to objects in it isn't garbage collected. The array in the Stack still exists as long as the Stack does. The reference element is just set to null. The reference still exists, but it's now null and it no longer refers to the object.

Clearing the reference helps with memory efficiency, by allowing garbage collection to reclaim the memory on the popped object, assuming that nothing else refers to that object as well. Without clearing the reference, the object would never be garbage collected, unless the Stack itself (with its array referring to the object) was garbage collected.

Assigning null to objects in every application after their use

  • no, don't do that, except for specific cases such as static fields or when you know a variable/field lives a lot longer than the code referencing it
  • yes, but with a working knowledge of your VM's limits (and how to cause blocks of memory to be held accidentally)
  • n/a

Java: setting a reference to null won't affect the object

When you write:

// Moved [] to make it more idiomatic
String[] sarr = {s1, s2, s3};

That copies the values of s1, s2 and s3 (which are references, not objects) into the array. When the statement has executed, the variables are entirely independent of the array. Changing the value of any of the s1, s2, s3 variables to refer to a different string doesn't affect the contents of the array at all.

It's exactly the same as with other assignments, e.g.

string x = "hello";
string y = x;
x = null; // Doesn't affect y

and method arguments, too.

Note that the garbage collection part is a red herring here - while obviously understanding this is important to understanding garbage collection, the reverse isn't true. The important points are to understand that:

  • The values of s1, s2, and s3 and the elements of the array are references, not objects.
  • The values are copied when creating the array, so changing the variable afterwards doesn't make any difference

Now, to take the example a bit further, consider:

StringBuilder sb = new StringBuilder("Hello");
StringBuilder[] array = { sb };

sb.append(" world");
System.out.println(array[0]);

This will print "Hello world" because here we've only got a single StringBuilder object, which both sb and array[0] refer to. Changing the data inside that object (which isn't the same as changing sb to refer to a different object) makes the change visible however you get at it. This is like me giving the address of my house to two people - if one of them paints my house red, the other person will see that as well.

Garbage Collection works automatically or manually?

From here

In a programming language like C, allocating and deallocating memory is a manual process. In Java, process of deallocating memory is handled automatically by the garbage collector.

I'd suggest you reading the full article. You will have a good grasp of how GC works in Java. HTH.

Making static reference variable nullify will ever be garbage collected by java?

Yes if you nullify it will be garbage collected, but assigning an Activity to a static variable is an anti-pattern and must be avoided at all costs, even if you eventually nullify it, because this is easiest way to leak an Activity.

In fact, Android Studio should already be giving you a warning about it.

Here you have some literature to avoid leaking memory.

java garbage collection and null reference

c3 is a local handle with a null reference, it does not point (and hever has pointed) to an allocated object. Therefore there's nothing to GC.



Related Topics



Leave a reply



Submit