Android Recycle Call

ID

kotlin.android_recycle_call

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Kotlin

Tags

CWE:672, android, reliability

Description

Reports method calls on a recyclable Android resource variable (TypedArray, VelocityTracker, MotionEvent, Parcel) that occur after recycle() has already been called on the same variable within the same function body. The underlying object is returned to a shared pool by recycle() and any further use may throw, return stale data, or corrupt state observed by other callers.

Rationale

fun bad() {
    val vt = VelocityTracker.obtain()
    vt.recycle()
    vt.getXVelocity()                    // FLAW — call after recycle
}

fun good() {
    val vt = VelocityTracker.obtain()
    vt.addMovement(null)
    vt.recycle()                         // OK — recycle is the last call
}

The rule sorts every usage of the binding in source order, marks the binding recycled at the first recycle() call, then flags every subsequent method invocation on the same name. Branching and loops are not modelled — the analysis is intra-function and linear.

Remediation

  • Move recycle() to be the last operation on the binding.

  • Re-acquire the resource with a new obtain() call if work must continue after recycling.

  • Place recycle() inside try/finally so the cleanup runs once after all usage.