Sep 19, 2014

How String's substring function can cause memory leak in Java 6??

Hi friends, this is my first post on Java Insight blog. Hopefully this would be of little help to you.

Lets start off with String class, most widely used Java class may be.


We all use String's substring method so frequently while programming, but have you ever given a thought of how it works. How memory is managed? Can it lead to memory leaks? Truly speaking, I never had, until I stayed whole night in office debugging an application for memory leaks.


Enough of intro to engage you further I guess, so lets jump straightaway into action.




If you look substring method inside String class, you will figure out that it calls String (int offset, int count, char value []) constructor to create new String object. What is interesting here is value[] which is the same character array used to represent original string. Caught something?? No???... don't worry.. read it again... value[] is the same character array used to represent original string". This means it will
 keep an array of complete string on which sub-string function is being called. Thus, if original String is huge in size, it was 1 GB in my case, but only part of it is required, may be of size 5 characters may be, 1 GB of memory will still be occupied by that String. Look at below example:


String someLongString = new String("LONG STRING....");
String shortSubString = someLongString.substring(0, 3); // creates a copy of someLongString, but points only to first 3 charcters.
//....
//...



As you see below, what happens is whole someLongString will be retained inside the memory unless shortSubString gets garbage collected.

I hope this article would be of some help to you.

One final thing, as the title of the post says: "How String's substring function can cause memory leak in Java 6??", question is what if you are using Java 7 onwards. Good news! java guys have made changes to String class so you don't need to worry about it.

You can ask your questions in the comments section. I will be happy to answer them. Stay tuned for other interesting stuff in Java.

7 comments:

  1. Thanks Manoj. :)
    Very nice blog. Hope to see new posts soon.

    ReplyDelete
  2. Wow !! going good. keep it up. nice bog :)

    ReplyDelete
    Replies
    1. Thank You :)
      You can also follow us to stay updated with most recent posts :)

      Delete
  3. Hey Manoj... You have nicely explained the topic.. I would suggest if you could also write a blog on eclipse debugging and debugging procedures in oracle developer tools

    ReplyDelete