MumbleCloseable

Jim Mayer jim at pentastich.org
Fri Jun 28 21:36:56 PDT 2013


I agree with Rémi about deferring the open.  I think that the following
(completely untested) code would defer the file open into the execution
context of the terminal method and would be resource safe.  This version is
very specific to file I/O, but I think the basic idea could be easily
generalized.

private class BufferedReaderSupplier implements Supplier<String>, Closeable
{
  private final Path path;
  private final Charset cs;
  private BufferedReader br;

  public BufferedReaderSupplier(Path path, Charset cs) throws IOException {
    this.path = path;
    this.cs = cs;
    if (! Files.isReadable(path)) {
      throw new FileNotFoundException(path.toString());
    }
  }

  @Override
  public String get() {
    try {
      if (br == null) {
        br = Files.newBufferedReader(path, cs);
      }
      return br.readLine();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public void close() throws IOException {
    if (br != null) {
      br.close();
    }
  }
}

public static Stream<String> lines(Path path, Charset cs) throws
IOException {
  BufferedReaderSupplier supplier = new BufferedReaderSupplier(path, cs);
  return Stream.generate(supplier).onClose(Closeable.asRunnable(supplier));
}

Jim Mayer


On Fri, Jun 28, 2013 at 5:58 PM, Remi Forax <forax at univ-mlv.fr> wrote:

> On 06/28/2013 10:20 PM, Brian Goetz wrote:
>
>> public static Stream<String> lines(Path path, Charset cs) throws
>> IOException {
>>         BufferedReader br = Files.newBufferedReader(path, cs);
>>         return br.lines().onClose(Closeable.**asRunnable(br));
>>     }
>>
>
> This code, is leaky, it will not call close() on the buffered reader,
> if lines() or Closeable.asRunnable() throws an unchecked exception.
>
> As I said earlier, the only way to deal with that correctly is to
> open/close the reader only in the terminal method, not before.
>
> Rémi
>
>


More information about the lambda-libs-spec-observers mailing list