Win a copy of Five Lines of Code this week in the OO, Patterns, UML and Refactoring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

runtime.gc()

 
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.

 
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.
 
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).
 
    Bookmark Topic Watch Topic
  • New Topic