Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How unreferred values from string pool get removed?

Tags:

java

I'm curious how values from a string-pool get removed?

suppose:

String a = "ABC"; // has a reference of string-pool
String b = new String("ABC"); // has a heap reference

b = null;
a = null;

In case of GC, "ABC" from the heap gets collected but "ABC" is still in the pool (because its in permGen and GC would not affect it).

If we keep adding values like:

String c = "ABC"; // pointing to 'ABC' in the pool. 

for(int i=0; i< 10000; i++) {
  c = ""+i;
  // each iteration adds a new value in the pool. Previous values don't have a pointer.
}

What I want to know is:

  • Will the pool remove values that are not referred to? If not, it means that the pool is eating up unnecessary memory.
  • What is the point then because the JVM is using the pool?
  • When could this be a performance risk?
like image 974
Muneeb Nasir Avatar asked Sep 11 '15 14:09

Muneeb Nasir


1 Answers

As part of this code

String c = "ABC"; // pointing to 'ABC' in pool. 

for(int i=0; i< 10000; i++) {
  c = ""+i; // each iteration add new value in pool. and pervious values has no pointer  

}

Only two String objects will be in the pool, the two that come from the two String literals, "ABC" and "". Every other String created from the concatenation will be a regular object with regular GC behavior, ie. candidate for collection when they are no longer reachable.

The String values coming from String literals in the pool will not get collected as they are always reachable (YMMV with class loaders). String objects that are interned but don't come from literals should become candidates for GC in the regular manner.

More things to read:

  • What is the difference between "text" and new String("text")?
  • Garbage collection of String literals
like image 88
Sotirios Delimanolis Avatar answered Oct 04 '22 09:10

Sotirios Delimanolis