I have some doubts regarding Strings
Are they live on Heap or String pool?
And if on Heap then they will be garbage collected, if they are not reachable by any live thread.
And if on String pool then how they will be deleted or removed because as we know Garbage Collection happens only on heap.
7. What happens to the thread when garbage collection kicks off? Explanation: The thread is paused when garbage collection runs which slows the application performance.
A little bit on strings Strings in C# are immutable. What that means is that you cannot modify an existing string, you must create a new one. Also strings are objects – sequential read only collections of char objects – so they are allocated on the managed heap, and therefore managed by the Garbage Collector (GC).
An object is eligible to be garbage collected if its reference variable is lost from the program during execution. Sometimes they are also called unreachable objects. What is reference of an object?
String s = new String("abc");
the string object referred by s will be on heap and the string literal "abc" will be in string pool. The objects in the string pool will not be garbage collected. They are there to be reused during the lifetime of the program, to improve the performance.
They are all stored in the heap, but intern()
ed strings (including string literals in the source) are referenced from a pool in the String
class.
If they appear as literals in the source code, including constant string expressions (e.g. "a" + "b"
) then they will also be referenced from the Class
the appear in, which usually means they will last as long as the process runs.
Edit:
When you call intern()
on a string in your code it is also added to this pool, but because it uses weak references the string can still be garbage collected if it is no longer in use.
See also: interned Strings : Java Glossary
Quote from that article:
The collection of Strings registered in this HashMap is sometimes called the String pool. However, they are ordinary Objects and live on the heap just like any other (perhaps in an optimised way since interned Strings tend to be long lived).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With