Revisiting MayHoldCloseableResource
Ali Ebrahimi
ali.ebrahimi1781 at gmail.com
Tue Aug 13 14:20:42 PDT 2013
Hi,
On Tue, Aug 13, 2013 at 10:33 PM, Zhong Yu <zhong.j.yu at gmail.com> wrote:
> On Tue, Aug 13, 2013 at 12:24 PM, Kevin Bourrillion <kevinb at google.com>
> wrote:
> > On Tue, Aug 13, 2013 at 1:03 AM, Joshua Bloch <josh at bloch.us> wrote:
>
> > We have to view AutoCloseable as exposing the *ability* to be closed
> (which
> > may be a no-op), not as implying a burden to the caller that it *must* be
>
> Now the burden is on the programmer who must reason whether a stream
> needs to be closed, with some other information not conveyed by the
> type of the object.
>
> > closed. ByteArrayInputStream etc. already show that we can't effectively
>
> ByteArrayInputStream is a singular example that has been over played
> to argue against the general semantics of AutoCloseable.
>
> And it is probably a mistake to spec that its close() must have no
> effect. That spec is unnecessary and harmful. The close() could gain a
> side effect, e.g. dereference the byte array; and a subclass may wish
> to attach additional effects to close().
>
> > surface that responsibility in the type hierarchy alone. There needs to
> be
> > a separate means for static analyses to judge whether an instance
> *needed* to
> > be closed.
>
> I think some destructor like utility is probably the cleanest
> solution. For example
>
> try(Scope scope = new Scope())
> {
> Files.walk(scope, dir).flatMap(file->Files.lines(scope, file))
> }
>
> static Stream<Path> File.walk(scope, dir)
> {
> ... scope.onExit( free resources );
> }
>
> or use thread local to further simply the syntax
>
> Scope.exec(()->
> {
> Files.walk(dir).flatMap(Files::lines);
> });
>
> static Stream<Path> File.walk(dir)
> {
> scope = Scope.current();
> if(scope==null) throw new Exception();
> return walk(scope, dir);
> }
>
>
> What about if we have this:
public Stream<> getPathTreeStream( String dir){
return Files.walk(dir);
}
Stream operations are mostly lazy, So close should be invoked at
appropriate time Not Stream creation time: After stream traversal (Or
stream operatin) completed
So closeability is characteristic of some Streams Not All.
So I suggest one simple Solution:
1) Add close method to BaseStream (Consider retrofitting BaseStream As
AutoCloseable for java 9 if needed)
2) Add new characteristic flag CLOSEABLE to Stream's Characteristis at
Stream creation time
3) Stream operation itself invokes close method At end as required.
Advantage: No verbose TWR for stream usage code
Ali
More information about the lambda-libs-spec-observers
mailing list