What if Size of String Pool Exceeds?

前端 未结 2 1987
别那么骄傲
别那么骄傲 2021-01-04 13:01

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 runti

2条回答
  •  温柔的废话
    2021-01-04 13:58

    There is a long discussion with real code examples at JavaRanch.

    The general output is the following:

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

提交回复
热议问题