說明

All AutoCloseable resources (streams, connections, readers) must be managed via try-with-resources or declared in a finally block. Never rely on garbage collection to close resources.

為什麼重要

  • Resource exhaustion — unclosed file handles / DB connections leak until the process runs out
  • Data corruption — unclosed write streams may flush partial data
  • Security — unclosed network connections can be hijacked

Enforcement

OBL_UNSATISFIED_OBLIGATION — method may fail to clean up stream or resource.

Rule: java:S2095 — Resources should be closed

正例

try (var stream = Files.lines(path)) {
    return stream.filter(line -> line.contains(keyword)).toList();
} // ✅ auto-closed

反例

var stream = Files.lines(path);
var result = stream.filter(line -> line.contains(keyword)).toList();
return result; // ❌ stream never closed