How to remove unnecessary values ​​from a row pool?

I am wondering how the values ​​are removed from the row pool?

suppose:

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

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

If we add values ​​such as:

 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:

  • Does the pool delete values ​​that are not referenced? If not, it means that the pool has unnecessary memory.
  • What is the point when the JVM uses the pool?
  • When can this be a performance risk?
+5
source share
1 answer

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 } 

There will be only two String objects in the pool, two of two String literals, "ABC" and "" . Every other String created from concatenation will be a regular object with regular GC behavior, i.e. candidate to collect when they are no longer available.

String values ​​coming from String literals in the pool will not be collected because they are always reachable (YMMV with class loaders). String objects that are interned, but not from literals, should regularly become candidates for the GC.

More things to read:

+3
source

All Articles