Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will an element be garbage collected if there is a reference to its field?

I.e., in

class A {
    public String s;
}

and

A a1 = new A();
a1.s = "bla";
A a2 = new A();
a2.s = a1.s;
a1 = null;

will a1 be garbage collected or is the reference to a1.s permitting it from being collected (and I should rather do a deep copy, a2.s = new String(a1.s))?

Thanks a lot in advance!

like image 364
dotwin Avatar asked Jul 02 '13 06:07

dotwin


People also ask

Is garbage collection based on reference?

The main concept that garbage collection algorithms rely on is the concept of reference. Within the context of memory management, an object is said to reference another object if the former has access to the latter (either implicitly or explicitly).

How do you know if an object is garbage collected?

An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects.

Can an object be garbage collected while it is still reachable?

It's possible to have unused objects that are still reachable by an application because the developer simply forgot to dereference them. Such objects cannot be garbage-collected.


1 Answers

If an object holds a reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.

See this link for further information.

like image 157
Maroun Avatar answered Oct 23 '22 06:10

Maroun