Please disable adblock to view this page.

← Go home

Java Memory Management and Garbage Collection

java-display

April 29, 2017
Published By : Pratik Kataria
Categorised in:

Automatic Memory Management

  • Objects are allocated memory automatically unlike in C or C++
  • Objects are created in Heap Memory.
    • Heap memory is a little slower than stack. But, heap is more dynamic.
    • Complex objects are always stored in heap.
  • If a variable references an object, it is retained i.e. it won’t be available for garbage collection.
    In other words, as long as a variable can be address in code, the object will be available.
  • When all the references of object expire, it is eligible for garbage collection.
    However, garbage collection decides when to do that.

Lifetime of References

  • Local variables within method or code block expire with the end of its scope.
  • Explicitly dereferenced variables with null keyword are eligible for garbage collection.
    String tempStr = "Something";
    tempStr = null; //this is dereferencing.

    Here, the object tempStr might be available for sometime but if garbage collector picks it then it will not exist.

Garbage Collector

  • Runs in its own thread.
  • You might detect it in execution as a little pause while the program is executing.
  • It can destroy dereferenced objects and reclaim their memory.
    But it is not required to do that.
  • Programmer cannot make the garbage collector work.
  • Programmer can request garbage collection, however there is no guarantee.
    E.g. Methods like System.gc() and Runtime.gc()
  • If no memory is available for newly created object, then the system throws:
    OutOfMemoryError (TIP: this is an exception)

What can you do?

  • Lower the number of objects you create.
  • Understand when objects are created.
  • Try to re-use objects.
  • Some important methods:
    • Runtime.maxMemory()
    • Runtime.totalMemory()
  • Use command-line options to manage available heap memory:
    • java -Xms256s HelloWorld    (Sets initial heap size)
    • java -Xmx256m HelloWorld   (Sets maximum heap size)
    • java -Xmn256n HelloWorld    (Sets heap size for new objects)