Wednesday 27 May 2015

Will String literals be garbage collected ?

EDIT: Below is for till JAVA6, in JAVA 7 String literal pool has been moved from PermGen to Normal Heap,

Adv : PermGen Size is fixed and less, where Normal HEAP size is increasable and large

Still LITERAL pool is in separate space of Heap.



-----



Why
Java Says Only one copy of String, every one get's the reference of the same.

NOte: When you create same string  value "Bangalore" via New String, jvm creates new object in Heap but internally, that new object will also point to same String available in String literal pool

String first = "bangalore"
String second = "bangalore"

first==second // Troe, Just referenc check, both points to same object in SLT/SCP

String firstStr = new String("bangalore");
String secondStr = new String("bangalore");

firstStr ==secondStr //False, both have new address reference in HEAP, although, both heap may point to same string in SLP/SCP

firstStr.squals(secondStr) // TRUE,Since String overrides the equal meth of java.lang.Object and checks char by char of equality,default implementation in Object class just check for reference equality. Obj1==Obj2


WHY STRING WAS MADE SPECIAL:
1. To improve performance, if same string is created again, java just return the reference from SLP .
2. Issue with this approach was , if all thread points to same String and thread1 makes modification, all other threads will have a new undesirable value.

3. to overcome that, they made String objects immutable(Final, so one extends and change the behavior, fields were private(If public then fields value can be changed with object reference, so setter method, all the alteration functions creates new string object and return the new reference.

Also if String is your key in HashMap, if String was not immutable, any change to reference would directly change the Key in hashmap, and receivers of hashMap, would not be able to search your entry with already agreed key.



Stored where

It's added in to Array of String called "String constant pool" , placed inside "PERMGEN" SECTION OF HEAP

Never garbage collected


Who has the reference ?

All the codes which created it, and codes information will be available in the CLASS which is loaded by a classloader, and default classloader never gets GC'ed.

Hence those string will live there forever.

Now does Actual String Object resides in Old/Young generation and Constant pool array, holds only references to it ?

I need to find out.

No comments:

Post a Comment