Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection and Strings

Tags:

java

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.

like image 426
GuruKulki Avatar asked Feb 04 '10 18:02

GuruKulki


People also ask

What happens to the thread when garbage collection?

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.

Are strings garbage collected C#?

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

Which objects are garbage collected?

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?


2 Answers

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.

like image 86
Zacky112 Avatar answered Oct 11 '22 23:10

Zacky112


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

like image 45
finnw Avatar answered Oct 11 '22 23:10

finnw