0

Here is the function:

String gen() {
      String raw_content = "";
      String line;
      for (int i=0; i<10000; i++) {
        line = randString();
        raw_content += line + "\n";
      }
      return  raw_content;
}

When I call gen() for 100 times in main(), my program will stuck. I suspect this is related to memory leak caused by Java String. So will the no-longer used memory be freed by JVM automatically? How to fix this?

Thanks!

user3462510
  • 106
  • 7
  • 1
    Use a `StringBuilder`. – Paul Boddington Apr 02 '15 at 02:35
  • 2
    can you post the code for `randString()`? – Mshnik Apr 02 '15 at 02:35
  • fot the newline character look at http://stackoverflow.com/questions/207947/java-how-do-i-get-a-platform-independent-new-line-character – lordkain Apr 02 '15 at 02:39
  • `line` is completely worthless no? – ChiefTwoPencils Apr 02 '15 at 02:39
  • 2
    There is no memory leak in the code you have shown us. – Radiodef Apr 02 '15 at 02:40
  • In fact I intentionally used the variable "line" since I want to know whether its memery will be freed by JVM automatically. – user3462510 Apr 02 '15 at 02:43
  • Freed when? It's scope is limited to `gen`. – ChiefTwoPencils Apr 02 '15 at 02:46
  • 2
    There is no memory leak, `raw_content` keeps getting longer and longer, and every iteration involves copying the old String value to a new one. This drives GC crazy and performance goes into the toilet. Eventually, if you raised the iteration limit, you would get an out of storage condition because the array was so long, but it would take forever to get there due to the constant copy/GC cycle. – Hot Licks Apr 02 '15 at 02:47
  • 1
    The only "memory leak" is the _ten thousand_ useless objects you're creating just to throw them away. The garbage collector isn't magic --- it takes time to clean up all that trash. You're not "leaking" memory, you're just wasting memory. – Kevin J. Chase Apr 02 '15 at 04:54

1 Answers1

1

To make a long story short, in java (and other JVM languages), you don't have to care about memory allocation at all. You really shouldn't be worrying about it - at some time after all references to it have been lost, it'll be freed up by the garbage collecting thread. See: Garbage Collection in Java.

Your problem has less to do with memory and more that your function is just really time intensive (as Hot Licks said in comment). Strings in Java are immutable, so when you say raw_content += line + "\n"; you're really creating a new string of raw_content + line + "\n" and setting raw_content equal to that. If rand_string() returns long results, this will become an egregiously long string. If you really want to perform this function, StringBuilders are the way to go to at least reduce it from O(N^2) to O(N). If you're just looking for a memory exercise, you don't have to actually do any changes - just read the above article.

Mshnik
  • 7,032
  • 1
  • 25
  • 38