What if Size of String Pool Exceeds?
java, string
Solution
There is a long discussion with real code examples at JavaRanch.
The general output is the following:
- If a string is added to constant pool at RUNTIME using String.intern(), it can be garbage collected after it is no longer in use. Most probably, the string pool keeps only soft references to added strings, thus allowing to garbage collect them (can't be sure, because String.intern() is a native method).
- If a string is a COMPILE time constant, it is added to the constant pool of the corresponding class. Therefore, it can be garbage collected only after the class is unloaded.
The answer to your question is: the only way how you can get OutOfMemoryError because of String constants is to load lot's of classes with many string literals computed at compile time. Then you can eventually exceed maximum size of PermGen space. But this will happen at the time you load classes into memory (e.g., start your application, deploy project to a WebServer, dynamically load new library, etc.)
Problem
In Java, String literals in String Constant Pool are not garbage collected, since they are referenced from Table of references which is created by instance of runtime in order to optimize space. If Size of String literal pool exceeds then, Since each String in String literal pool has reference hence it will be not eligible for GC. how it is handled by JVM ?