# Reference Leak

Find incorrect uses of soft or weak references.
Copyright (c) 2020,2023 IBM Corporation. All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 which accompanies this distribution, and is available at https://www.eclipse.org/legal/epl-2.0/

# Motivation

Soft references java.lang.ref.SoftReference and weak references java.lang.ref.WeakReference are used to keep references to objects which can be cleared by garbage collection if there are no other strong references.

Soft references can be used for object caching, so that an object can usually be retained for fast access, but if memory is tight then garbage collection can break the link and free the object. Next time it is needed then the application program can regenerate the object.

Weak references can be used in a weak hash map java.util.WeakHashMap to hold information associated with another object, but if that object is no longer available then the associated information can be freed too.

Sometimes an error in the application program can mean that the object which is supposed to be softly or weakly referenced is also strongly retained by the reference object. For example the key of a weak hash map is weakly retained, but if there is a strong reference to it from the value of the weak hash map entry then the object will never be freed.

# Operation

This query performs the following steps:

1. For each reference object supplied to the query, find the object referred to by the reference object via the reference field.
2. Find all the objects strongly retained by the reference object.
3. Find if the object from the first step is also in the second list. If so:
   1. Generate a tree with a path showing the reference object, the referent and the strong path to the referent.
   2. Generate a tree showing paths from GC roots to the reference object including showing field names.

This type of query is also performed by the component report.

# Arguments

Argument
Description
objects
Reference objects for which the reference leaks query should be run.
-referent_attribute
The referent field name for the reference objects. The default is referent
-maxresults
The maximum number of objects for which a tree should be shown.
-maxobjs
The maximum number of objects to be examined for leaks. A random selection of the total objects will be chosen.
-factor
For common paths, how much to truncate the path as the number of objects reduces.

# Result