Utilities of auto close
Zhong Yu
zhong.j.yu at gmail.com
Fri Jun 21 07:41:48 PDT 2013
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