Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

runtime.gc()

 
Kee Kee moon
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Is it necessary to add the following codes into my program, or let it auto clean up. What are pros and cons.)

Runtime runtime = Runtime.getRuntime();
runtime.gc();
runtime.runFinalization();

Thank you.

 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, there should never be a need to call those methods. If you've written your code correctly and provided the right parameters at JVM startup, those will have little or no effect.

In certain special cases, things might run more smoothly (fewer noticeable bumps) at the cost of slightly lower overall throughput if you explicitly invoke GC, and in certain rare cases, explicitly invoking GC might prevent an OutOfMemoryError, but I would only add it as a last resort, after first examining my design and code and reviewing my startup JVM params.
 
Paul Balm
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in certain rare cases, explicitly invoking GC might prevent an OutOfMemoryError


Really? I thought the JVM guarantees that no OutOfMemoryError is thrown if memory can be freed up by garbage collection?

In any case, I agree that if you have OutOfMemoryErrors, calling Runtime.gc() is never a solution. You need to look at ways to use less memory (allow objects to be garbage collected) first, then consider other options like writing rarely accessed data to disk, distributing the work over more machines or scaling up your machines (add memory).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic