Resource leak Medium

Allocated resources are not released properly. This can slow down or crash your system. They must be closed along all paths to prevent a resource leak.

Detector ID
java/resource-leak@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public List<Path> autoCloseableStreamNoncompliant(final Path path) throws Exception {
2    final List<Path> files;
3    // Noncompliant: does not close the auto-closeable streams of file system objects.
4    Stream<Path> pathStream = Files.walk(path);
5    files = pathStream.filter(p -> Files.isRegularFile(p))
6            .map(path::relativize)
7            .collect(Collectors.toList());
8    log.info("Relativized files: {}", files);
9    return files;
10}

Compliant example

1public List<Path> autoCloseableStreamCompliant(final Path path) throws Exception {
2    final List<Path> files;
3    // Compliant: the try-with-resources block auto-closes any auto-closeable streams when done.
4    try (Stream<Path> pathStream = Files.walk(path)) {
5        files = pathStream.filter(p -> Files.isRegularFile(p))
6                .map(path::relativize)
7                .collect(Collectors.toList());
8    }
9    log.info("Relativized files: {}", files);
10    return files;
11}