Java Reference
In-Depth Information
without the matching removeActionListener calls, which means the program
is vulnerable to future memory leaks. It also takes a singleton class and
changes it to a regular object, which must be instantiated for each use. The
singleton may have been initially created to conserve system resources.
Solution 3: Weaken the reference
With the introduction of version 1.2, Java offers additional types of refer-
ences that can be used to solve this problem. In addition to the standard
object reference, Java has specialized reference objects that can work with the
garbage collector in special circumstances. There are three types: weak, soft,
and phantom references. For this solution, we need weak references. To the
garbage collector, an object that can be reached only by using a weak refer-
ence is called weakly reachable and is a candidate for garbage collection. In
figure 6.3, objects C and D are weakly reachable. Weak references can be
placed in collections with longer life cycles, in situations that might normally
inhibit garbage collection. Because objects can be garbage collected, the null
condition should always be checked whenever you're accessing an object
through a weak reference.
Reference objects simplify memory management
Each solution has its advantages and disadvantages. Weak references provide a
generic solution that's suitable for frameworks and tools, like visual program-
ming environments, but it isn't as clean a solution as explicitly removing each
References: Strong
C and D
are weakly
Figure 6.3 Weak references can be used to assist the garbage collector. An object is weakly
reachable if it can be reached only through a weak reference. Weakly reachable objects are
candidates for garbage collection.
Search WWH ::

Custom Search