Tuesday, January 3, 2012

Garbage Collection

Garbage Collection

  • Unlike some OO languages, Java does not support an explicit destructor method to delete an object from memory.
    • Instead, unused objects are deleted by a process known as garbage collection.
  • The JVM automatically runs garbage collection periodically. Garbage collection:
    • Identifies objects no longer in use (no references)
    • Finalizes those objects (deconstructs them)
    • Frees up memory used by destroyed objects
    • Defragments memory
  • Garbage collection introduces overhead, and can have a major affect on Java application performance.
    • The goal is to avoid how often and how long GC runs.
    • Programmatically, try to avoid unnecessary object creation and deletion.
    • Most JVMs have tuning parameters that affect GC performance.
Benefits of garbage collection:
  • Frees up programmers from having to manage memory. Manually identifying unused objects (as in a language such as C++) is not a trivial task, especially when programs get so complex that the responsibility of object destruction and memory deallocation becomes vague.
  • Ensures integrity of programs:
    • Prevents memory leaks — each object is tracked down and disposed off as soon as it is no longer used.
    • Prevents deallocation of objects that are still in use or have already been released. In Java it is impossible to explicitly deallocate an object or use one that has already been deallocated. In a language such as C++ dereferencing null pointers or double-freeing objects typically crashes the program.
Through Java command-line switches (java -X), you can:
  • Set minimum amount of memory (e.g. -Xmn)
  • Set maximum amount of memory (e.g. -Xmx, -Xss)
  • Tune GC and memory integrity (e.g. -XX:+UseParallelGC)
For more information, see: http://java.sun.com/docs/hotspot/VMOptions.html and http://www.petefreitag.com/articles/gctuning/

No comments: