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!
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).
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.
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.
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.
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