1

userText will be a string of around 7000 characters in different languages. I was wondering how the strings will be garbage collected after executing this code. For suppose after unescapeHtml4 userText is assigned a new value and the same thing with after replace.

what happens to the previous string of userText. will they be in string pool or will be removed by the garbage collector.

String userText = context.getRequestParameter( "addedText");
if ( someCondition)
{
   userText = StringEscapeUtils.unescapeHtml4( userText ) );
}
else
{
  userText =  userText.replace( charsequence1, charsequence2 );
}

-- some logic using userText ---

3
  • 2
    7000 chars is pretty much as far away from "large" as it can get. Commented Oct 17, 2017 at 17:34
  • @luk2302 what about 6999? Or... 6998 (this could go on a while...) :) Commented Oct 17, 2017 at 17:49
  • @AndyTurner: when 7000 are far away from being large, these smaller numbers are as well. Even multiplying it by ten wouldn’t make it worth thinking about garbage collection. Commented Oct 18, 2017 at 8:01

1 Answer 1

1
//This String object will live as long as "context" will live
String userText = context.getRequestParameter( "addedText"); //"addedText" goes to a String Pool
if ( someCondition)
{
//This String object will live as long as "userText" variable is accessible
   userText = StringEscapeUtils.unescapeHtml4( userText ) );
}
else
{
//This String object will live as long as "userText" variable is accessible
  userText =  userText.replace( charsequence1, charsequence2 );
}

Verb "live" means existence of the object before GC will have a right to kill it;-)

Sign up to request clarification or add additional context in comments.

8 Comments

so the text from context.getRequestParameter( "addedText") will be in string constant pool as long as the application is up. GC doesn't remove from SCP?
Dmitry wrote that "addedText" will be there, not context.getRequestParameter( "addedText").
oh sorry about that, my doubt is what happens to all the strings in SPC which were from either the one we got from context or which we get from unescapeHtml4 or replace methods. will they be in SPC till the application is running.
String object goes to the pool only if its String literal like "addedText" or method String.intern() invoked on the string object. Otherwise String object will not be in SP.
It is more likely that you misunderstood what these answers actually wrote. I bet my shoes that they are about something like new String("someLiteral"); and that literal String goes to the pool.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.