Gyh's Braindump

Java Garbage Collector

tags
Java, Programming Language Concept
source
DT-On Java 8

Facts easily got mistaken

  • objects might not get garbage collected
  • garbage collection is not destruction
  • garbage collection is only about memory

Use Heap != Slow Speed

  • think C++ use heap as a yard -> search the whole yard when finding an object
  • think Java use heap as an stack -> JVM implementation

Technique

positioneaseboxintervaldue
front2.5036.002021-01-26T23:38:27Z

Reference Counting

  • each object contains a reference
    • a reference attached, count + 1
    • a reference goes out of scope or is set to null, count - 1
  • the collector moves along the list of objects, release ones whose counting is 0

Circular Reference

One problem is that when objects circularly refer to each other, their counting will never be zero while still being garbage.

Adaptive Scheme

Finding starts from references

General Idea: Any non-dead object must ultimately be traceable back to a reference that lives either on the stack or in static storage.

  • start in the stack and in the static storage and walk through all references
  • for each object found, follow references in that object

No Circular Reference issue.

Stop and Copy

After finding the objects:

  • each live object is copied from one heap to another, leaving behind all garbage
  • all reference (stack, static storage, inside objects) updated

Issues:

  1. have two heaps, maintaining twice as much memory as needed
  2. when the process become stable, less garbage generated, copying process seems wasteful

Mark and Sweep

Slow, but when little new garbage generated, it’s fast. (?)

Also stops the process.

After finding the objects:

  • set a flag - the object isn’t collected yet
  • after all objects found, sweep begins:
    • dead objects are released

Issue:

  • cause fragmented heap

Adaptive Way

When all objects are long-lived, JVM switches to use mark-and-sweep; when the heap starts to become fragmented, JVM switches to use stop-and-copy.

Links to this note