0

Quoting this page:

How many objects will be eligible for GC here?

String s = "hello";
Character ch1 = 1;
Character ch2 = 1;
ch1 = null;
s = null; 

I believe the answer is 1.

I would like to understand how it works in Java 6.

My understanding at the moment:

String is going to the pool. Later, there is no reference to it. So, according to this answer (I don't understand that part about classloader, can you clarify it?), String pool will most likely not be garbage collected...

Ok, Characters. There is this optimization in Java that will cause that ch1 and ch2 will point the same object. So, this small Characters are also going to some pool. But, despite ch1 is null, we still can access 1 with ch2 reference.

So, my answer at the moment would be 0.

Am I right in every step? If not, please correct me. Could you please provide an explanation how does it work exactly?

Community
  • 1
  • 1
Adam Stelmaszczyk
  • 19,665
  • 4
  • 70
  • 110
  • 1
    Considering the sentence before the cited part: “*Unlike the String pool for literals this "cache" does not affect GC*” and which point the author wanted to make, it seems they simply have *forgotten* to put a `ch2 = null;` statement into the code. They wanted to point out that the `Character` pool does not necessarily keep the object alive (unlike `String` pool), but by keeping it referenced in `ch2`, this point was destroyed. However, as an *implementation detail*, the reference implementation’s pool *does* keep the `Character` objects alive via a `static` variable. Case closed…or…not? – Holger Jun 08 '20 at 16:43
  • 1
    As elaborated in [Can java finalize an object when it is still in scope?](https://stackoverflow.com/a/24380219/2711488), local variables do not necessarily keep their referents alive anyway. Generally, every object may get garbage collected, if the application can’t notice. So neither pool needs to keep objects alive. Further, in most common implementations, `String` is a wrapper around an array object, in other words, consists of two objects. So the formally correct answer would be, 0, 1, 2, or 3 objects are eligible, depending on the implementation; we just don’t know and don’t need to know… – Holger Jun 08 '20 at 16:49

1 Answers1

3

Your answer "nothing gets collected" is right, at least as long the class defining the string lies around.

"hello" is a string literal and the class it appears in references it. As long as the class is reachable, the literal stays.

A class can be GC'd, too. But every class references its classloader and is referenced by it. Normally, you don't care about classloaders, as you use the default one and it (and all your classes) stay until the end.

Some application (e.g., web servers) need to be able to load and unload some code (e.g., servlet) dynamically. That's where classloaders get used.

maaartinus
  • 44,714
  • 32
  • 161
  • 320