Java Garbage Collector

  • Runs in its own thread
  • Can destroy dereferenced objects,but not required
  • Cannot force garbage collection

System Methods

  • System.gc() & Runtime.gc() can request garbage collection,but there's no guarantee it will happen.
  • OutOfMemoryError will occur when there's no memory for newly reuqiured object. [例如:数组越界]

Managing Memory Tips

  • Minimize the number of objects you create.
  • Use methods to find out how much memory is avaiable if necessary.
  • Runtime.maxMemory()
  • Runtime.totalMemory()

Set Avaiable Memory

Use command-line options to mange amount of avaiable heap memory:

java -Xms256s HelloWorld Initial heap size

java -Xmx256m HelloWorld Maximum heap size

java -Xmn256n HelloWorld Heap size for young generation objects