Files.write can leak file descriptor in the exception case in OpenJDK 8

Solution Verified - Updated -

Issue

In the exception case, similar to the one below, Files.write leaks, and instead of creating only one file descriptor not many. Example:

public static Path write(Path path, Iterable<? extends CharSequence> lines,
                             Charset cs, OpenOption... options)
        throws IOException
    {
        // ensure lines is not null before opening file
        Objects.requireNonNull(lines);
        CharsetEncoder encoder = cs.newEncoder();
        OutputStream out = newOutputStream(path, options);
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, encoder))) {
            for (CharSequence line: lines) {
                writer.append(line);
                writer.newLine();
            }
        }
        return path;
    } 

The leak may lead to a FileSystemException.

Note: Depending on ulimit -n setting the reproducer might behave differently.

Environment

  • OpenJDK 8 (1.8.242 or older)

Subscriber exclusive content

A Red Hat subscription provides unlimited access to our knowledgebase, tools, and much more.

Current Customers and Partners

Log in for full access

Log In

New to Red Hat?

Learn more about Red Hat subscriptions

Using a Red Hat product through a public cloud?

How to access this content