Utilities of auto close

Jed Wesley-Smith jed at wesleysmith.io
Sun Jun 23 22:16:20 PDT 2013


What about loan pattern:

interface Managed<A> {
  <B> doManaged(Function<A, B> f)
}

usage is:

Managed<Stream> mgr = new Managed<Stream>() {
  public <B> B doManaged(doManaged(Function<Stream, B> f) {
    Stream stream = open();
    try { f(stream); }
    finally { close(stream); }
  }
}



On 22 June 2013 00:41, Zhong Yu <zhong.j.yu at gmail.com> wrote:

> EG is discussing the issue of closing a Stream that ties to IO
> resources, and I'd like to throw in my 2 cents.
>
> Background: some new IO methods return Stream of things, for example
>
>     class Files
>         /** return a stream of entries in the dir */
>         static Stream<Path> list(Path dir);
>
> The problem is some IO resources are tied up and they need to be freed
> as soon as the Stream is no longer used.
>
> The current solution is
>
>         interface CloseableStream<T> extends Stream<T>, AutoCloseable
>
>         static CloseableStream<Path> list(Path dir);
>
> EG is discussing an alternative that makes all Streams AutoCloseable
>
>         interface Stream<T> extends AutoCloseable
>
> Some disagree with that approach, since most Streams do not need to be
> closed.
>
> ==
> My proposal:
>
> It's better to move the business of close() away from Stream to some
> surrounding constructs. For example:
>
>     try(Scope scope = Scope.newInstance())
>     {
>         Stream<Path> entries = Files.list(scope, dir);
>     }
>
>    interface Scope extends AutoCloseable
>     {
>         void onClose(Runnable action);
>
>         void close();
>     }
>
>     static Stream<Path> list(Scope scope, Path dir)
>     {
>         ...
>         scope.onClose( ()->{ free resources } );
>         ...
>     }
>
>
> Scope provides generic destructor-like functionality, orthogonal to
> resource types.
>
> Zhong Yu
>
>


More information about the lambda-dev mailing list