Skip to content

[java] CloseResource: False positive with resource being closed in method #4623

Closed

Description

@Han-Cui

Affects PMD Version: 7.0.0

Rule: CloseResource

Please provide the rule name and a link to the rule documentation:
https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html#closeresource

Description:
PMD warns in line 11, while the resource c gets closed in the function closeConnection.
Code Sample demonstrating the issue:
Maybe a false positive:

import java.sql.Connection;
import net.sourceforge.pmd.lang.java.rule.errorprone.closeresource.Pool;

public class Foo {

    void closeConnection(Connection c) {
        c.close();
    }

    void bar(Pool pool) {
        Connection c = pool.getConnection();
        try {
        } catch (Exception e) {
        } finally {
            // a lambda has the same effect
            closeConnection(c);
        }
    }

}

Compliant code:

import java.sql.Connection;
import net.sourceforge.pmd.lang.java.rule.errorprone.closeresource.Pool;

public class Foo {
    void bar(Pool pool) {
        Connection c = pool.getConnection();
        try {
        } catch (Exception e) {
        } finally {
            c.close();
        }
    }
}

Expected outcome:
No warnings.

Running PMD through: [CLI]

Activity

  1. added
    a:false-positive
    on Jul 3, 2023
  2. adangel commented on Jul 6, 2023

    @adangel
    Member

    You could configure the rule property "closeTargets" like this:

    <rule ref="category/java/errorprone.xml/CloseResource">
        <properties>
            <property name="closeTargets" value="closeConnection" />
        </properties>
    </rule>

    However, since this is all within one class, it would be nice if PMD could detect this on its own (through some basic call flow).

  3. added
    needs:pmd7-revalidation
    and removed
    needs:pmd7-revalidation
    on Mar 17, 2024
  4. changed the title [-][java] CloseResource: false positive with method call[/-] [+][java] CloseResource: False positive with resource being closed in method[/+] on Jun 23, 2026
  5. added this to the 7.27.0 milestone on Aug 13, 2026
  6. added a commit that references this issue on Aug 13, 2026
    c331aec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:false-positive

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions