Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder / StringBuffer with literal string in memory [duplicate]

example code:

StringBuffer sb = new StringBuffer("hi");
sb = null;

Question:

will the literal string "hi" somehow stay in memory, even after the StringBuffer has been garbage collected? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory?

like image 872
Artanis Avatar asked Dec 20 '18 21:12

Artanis


2 Answers

Yes, hi is a compile time constant so it gets interned by the compiler and resides in the string pool.

Moreover G1GC can perform String deduplication as part of JEP 192: String Deduplication in G1 in which case even if hi wasn't interned by javac it might be retained as part of the deduplication.

like image 174
Karol Dowbecki Avatar answered Oct 01 '22 22:10

Karol Dowbecki


A string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

JLS 11 > 3. Lexical Structure > 3.10.5. String Literals

like image 39
Andrew Tobilko Avatar answered Oct 02 '22 00:10

Andrew Tobilko