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?
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
-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. –
Engler © 2022 - 2024 — McMap. All rights reserved.