Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of String literals in Java 6 and Java 7(Oracle Jdk)

According to the famous book Head first Java Page 661:

"Garbage Collector doesn't go inside String pool."

After reading about the similar questions on SO, i have found mixed answers like:

  1. Garbage collection of String literals is same as normal objects. Read this
  2. Some answers say the opposite. Read answer here.

My Questions are:

  1. How were the string literals garbage collected in Java 6 and before ?

  2. And since in Java 7 , string literals will be created on heap, how the garbage collection of string literals will be different in Java 7 as compared to the java 6?

like image 322
Aman Arora Avatar asked Dec 05 '13 13:12

Aman Arora


1 Answers

String literals are interned.As of Java 7, the HotSpot JVM puts interned Strings in the heap, not permgen.

Prior to java 7, hotspot put interned Strings in permgen. However, interned Strings in permgen were garbage collected. Apparently, Class objects in permgen are also collectable, so everything in permgen is collectable, though permgen collection might not be enabled by default in some old JVMs.

String literals, being interned, would be a reference held by the declaring Class object to the String object in the intern pool. So the interned literal String would only be collected if the Class object that referred to it were also collected.

Picked up from : (Source).

like image 82
Aniket Thakur Avatar answered Oct 16 '22 13:10

Aniket Thakur