Search code examples
javagarbage-collectionjava-6scjp

Are interned constants eligible for GC?


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?


Solution

  • 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.