Skip to content

[java] CloseResource false positive #1911

@ben-manes

Description

@ben-manes

Affects PMD Version: 6.16
Rule: CloseResource
Description:
Sometimes code flows of many closeables is harder to express using nested try-with-resource blocks. Instead a Guava Closer can be used to aggregate the resources and close them, as in a single try-with-resource block. This is particularly useful when libraries don't implement AutoCloseable or to pass the aggregator to methods for resources that have to be closed at the end of the entire block.

In a case like below, I am receiving a CloseResource warning for SequenceWriter. Would it be possible to suppose Closer specifically if it cannot be deduced otherwise?

jsonSchema/csv/CsvToJson.java | 119 | Ensure that resources like this SequenceWriter object are closed after use

Code Sample demonstrating the issue:

try (Closer closer = Closer.create()) {
  CsvParser parser = new CsvParser(settings);
  closer.register(parser::stopParsing);
  parser.beginParsing(reader);
  ...
  SequenceWriter output = closer.register(mapper.writerFor(Entity.class)
      .withDefaultPrettyPrinter()
      .writeValuesAsArray(writer));
  while ((record = parser.parseNextRecord()) != null) {
    output.write(recordToEntity(record));
  }
} catch (IOException e) {
  throw new UncheckedIOException(e);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions