Aman Arora
Aman Arora

Reputation: 1252

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?

Upvotes: 11

Views: 611

Answers (1)

Aniket Thakur
Aniket Thakur

Reputation: 68935

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

Upvotes: 6

Related Questions