java - Does String interning causes a String to be both in heap and in native memory? -
here javadoc string#intern:
/** * returns canonical representation string object. * <p> * pool of strings, empty, maintained privately * class {@code string}. * <p> * when intern method invoked, if pool contains * string equal {@code string} object determined * {@link #equals(object)} method, string pool * returned. otherwise, {@code string} object added * pool , reference {@code string} object returned. * <p> * follows 2 strings {@code s} , {@code t}, * {@code s.intern() == t.intern()} {@code true} * if , if {@code s.equals(t)} {@code true}. * <p> * literal strings , string-valued constant expressions * interned. string literals defined in section 3.10.5 of * <cite>the java™ language specification</cite>. * * @return string has same contents string, * guaranteed pool of unique strings. */
lets have next code:
string ref1 = "ref"; string ref2 = ref1.intern();
at point of time when ref initialised, ref1 still in heap or not. i'm asking because if interning string without removing original reference double rss memory used java process.
if consider example, yes, ref1
still in heap, because both ref1
, ref2
point same instance. initialise ref1
string literal, , string literals automatically interned as described here:
moreover, string literal refers same instance of class string. because string literals - or, more generally, strings values of constant expressions (§15.28) - "interned" share unique instances, using method string.intern.
so, no double memory usage (if don't consider string being present in separate memory area holds content of class constantpool , class structure information).
to explain bit more in details how interning works, see example:
public class intern{ public static void main(string... args){ string str1="teststr"; string str2="teststr"; system.out.println("1. "+(str1==str2)); string str3=str1.intern(); system.out.println("2. "+(str1==str3)); string str4=new string("teststr"); system.out.println("3. "+(str1==str4)); string str5=str4.intern(); system.out.println("4. "+(str4==str5)); system.out.println("5. "+(str1==str5)); } }
you'll output:
1. true
strings loaded constant pool automatically interned string pool, result true both instances refer same interned object.
2. true
str3
refers string instance interned.
3. false
str4
new instance, nothing previous ones.
4. false
the throwaway str4
instance not point same object present since beginning in string pool.
5. true
str5
points our interned string expected.
it's important note before java 7(oracle implementation) interned strings stored in permgem (that since java 8 not exist anymore), since release have been moved heap. so, using older release of jvm peculiar memory issues appear when using interning feature massively.
for additional info on how interned strings managed in different releases, check nice post.
Comments
Post a Comment