Site hosted by Angelfire.com: Build your free website today!
scjp section 3: garbage collection
 
  • State the behaviour that is guaranteed by the garbage collection system.
  • Write code that explicitly makes objects eligible for garbage collection.
  • Recognise the point in a piece of source code at which an object becomes eligible for garbage collection.

Garbage Collection

  1. Memory Allocation
    • at run-time
    • method/local variables and method arguments(including references to objects) are allocated space on the stack
          - discarded when method returns
    • objects (when created with new)
      • go on the heap
      • have a longer lifetime - only collected when nothing is referencing it anymore
      • eventually cleaned up by the garbage collector, which is a low-priority thread, straight after the JVM calls the object's finalize() method

  2. System.gc() and Runtime.gc()
    • suggests to the JVM to run the garbage collector
    • garbage collection algorithm is platform dependant

  3. Setting References to null
    • when no longer using a reference, else can cause a memory leak - gc can't removed an object even though nothing is using it anymore
    • eg. popping an object off a stack (implemented as an array) - don't just want to decrement the index to the array, but also set myStack[oldIndex] = null;