Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if Size of String Pool Exceeds?

Tags:

java

string

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 ?

like image 234
kedar kamthe Avatar asked Apr 19 '12 08:04

kedar kamthe


2 Answers

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

like image 139
Andrey L Avatar answered Oct 04 '22 14:10

Andrey L


String literals can be collected when they are no longer needed. Usually this is not a problem if they appear in classes because there are other limits you are likely to reach if you attempt to load lots of classes e.g. Maximum Perm Gen.

Generally speaking, developers are smart enough not to over use the string literal pool and instead using databases or file to load the bulk of their data if its a non trivial size.

You can introduce a problem if you use String.intern() a lot in an attempt to optimise the space of your system. String.intern() is not free and becomes increasingly expensive if you add a large number (millions) of string into it. If this is a performance problem, it should be reasonably obvious to the developer when it is.

like image 36
Peter Lawrey Avatar answered Oct 04 '22 13:10

Peter Lawrey