6

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?
Tiny
  • 27,221
  • 105
  • 339
  • 599
Muneeb Nasir
  • 2,414
  • 4
  • 31
  • 54

1 Answers1

4

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:

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724