Recyclable Android Resource Not Recycled
ID |
java.android_missing_recycle |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
CWE:401, android, efficiency |
Description
Reports Android recyclable resource variables (TypedArray, VelocityTracker, MotionEvent, Parcel) that are acquired via factory methods (obtain(), obtainStyledAttributes(), etc.) but are never recycled within the same method body. Failing to recycle these objects wastes native memory and pooled resources, which can lead to performance degradation or out-of-memory conditions on resource-constrained devices.
Rationale
Android pools certain resource objects for reuse. When a component calls obtain(), it borrows an object from the pool. The object must be returned by calling recycle() once it is no longer needed.
VelocityTracker vt = VelocityTracker.obtain();
vt.addMovement(event);
// Bug: vt is never recycled -- the pooled object leaks
Remediation
Always call recycle() when the resource is no longer needed. Wrapping usage in a try-finally block ensures that recycling happens even when exceptions occur:
VelocityTracker vt = VelocityTracker.obtain();
try {
vt.addMovement(event);
vt.computeCurrentVelocity(1000);
} finally {
vt.recycle();
}