What will happen if there are many String literals on String Pool and it runs out of memory. Does it grow its size, if yes how? If not, what will happen if i try to create more String literals?
-
1Strings in the constant pool can be garbage collected if they are no longer needed – Hiren Jun 18 '15 at 09:49
-
1@Hiru, but doesn't JVM keep literals for reuse, that prevents its garbage collection? – Milan Pandey Jun 18 '15 at 09:59
1 Answers
First point first - STRING POOL Doesn't have String Literals
String Pool is a Collection of references that points to the String Objects.
When you write String = "hello" it creates that an String Object "hello" on the heap and will place an reference to this object in the String Literal Pool ( provided no Object is already there on the heap named "Hello")
Point to Note "hello" is added to the constant pool of the corresponding class. Therefore, it can be garbage collected only after the class is unloaded. So when the class is unloaded that Objects gets GC
What will happens?
String pooling is done through a process called string canonicalisation Which is a weakHashMap.This weakHashMap automatically clears out mapping when there is no other references to the keys or values. .ie the string will be garbage collected from the JVM.
Does it Grow in size?
NO STRING POOL DOESNOT GROW IN SIZE- It's is Compile Time Constant
How it Grow in Size ?
You need to specify -XX:StringTableSize=N, at the compile time where N is the string pool map size
At and at Last your question :
What happens if String Pool runs out of memory?
Simplest Answer : You get java.lang.OutOfMemoryError:java.lang.OutOfMemoryError: Java heap space
from java 7 onwards . While java.lang.OutOfMemoryError: PermGen space
in older version of java like 6

- 3,873
- 2
- 23
- 44
-
1+1 for later part of ur answer, however i m confused with the first part, "STRING POOL Doesn't have String Literals". I read, if i create a String using new operator, it creates object on heap while literal stays on Pool. it's bit confusing. Can u please help me out here? – Milan Pandey Jun 18 '15 at 11:23
-
1The `-XX:StringTableSize` option can be specified to a JVM *at startup time*, that’s not compile-time. It’s further important that the table size does not tell, how many strings can be stored. Storing more strings raises the chance of hash collisions, but the table handles collisions, it’s just that the lookup becomes less efficient. – Holger Aug 22 '22 at 13:59