Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8232003

(fs) Files.write can leak file descriptor in the exception case

XMLWordPrintable

    • b18
    • generic
    • linux
    • Not verified

        The code for Files.write() looks like this:

        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;
            }

        Even though the Javadoc says that the file descriptors are properly closed, the OutputStream fd is being leaked in case of Exceptions.

        In order to reproduce on Linux do the following:

        As root:
        $ mkdir /mnt/tmpfs
        $ mount -t tmpfs none -o size=4096 /mnt/tmpfs/

        Then as regular user do:
        $ cd /mnt/tmpfs
        $ java Reproducer

        In a separate terminal observe:
        $ jps | grep Reproducer
        31423 Reproducer
        $ lsof -p 31423 | grep /mnt/tmpfs/foo | wc -l
        92671

        It's expected that there is only one file descriptor pointing to /mnt/tmpfs/foo, not many.

        Depending on 'ulimit -n' setting the reproducer might behave slightly different.

              sgehwolf Severin Gehwolf
              sgehwolf Severin Gehwolf
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Created:
                Updated:
                Resolved: