Tuesday, July 10, 2007

Garbage Collection (with reference objects)

Part III

The Reference Object application programming interface (API) is new in the Java Development Kit (JDK) 1.2. This API allows a program to maintain special references to objects that allow the program to interact with the garbage collector in limited ways.

  • Unlike ordinary references, the reference in a reference object is treated specially by the garbage collector. A reference object encapsulates a reference to some other object, which is called the referent. The referent of a reference object is specified when the reference object is created.
  • Besides strongly reachable and unreachable objects, the Reference Objects API gives you strengths of object reachability. You can have softly, weakly and phantomly reachable objects and gain a limited amount of interaction with the garbage collector according to the strength of the object's reachability.
When an object is reachable from the root set by some chain of ordinary references (no reference objects involved), that object is said to be strongly reachable.

If, however, the only ways to reach an object involve at least one weak reference object, the object is said to be weakly reachable. An object is considered by the garbage collector to be in use if it is strongly reachable. Weakly reachable objects, like unreachable objects, are eligible for collection.




Fig.1: Adding reference objects to the heap

  • Unreachable objects (outside the strongly and weakly reachable areas) are not reachable from the root set.
  • Strongly reachable objects (inside the strongly reachable area to the lower left) are reachable through at least one path that does not go through a reference object.
  • Weakly reachable objects (inside the weakly reachable area shown enclosed with a dashed line to the upper-right) are not strongly reachable through any path, but reachable through at least one path that goes through a weak reference.

The diagram above shows two paths to the object on the heap with the X. It can be reached through the weak reference, and directly from the stack without going through a weak reference object. The object with the X is strongly reachable and not weakly reachable because one path leads to it from the root set without going through a reference object.

The garbage collection behavior for this object is the same as other strongly reachable objects until it is no longer reachable from the root set, at which time it becomes weakly reachable.

No comments: