Using the Java 8 Stream API, I would like to register a \"completion hook\", along the lines of:
Stream stream = Stream.of(\"a\",
The simplest solution is to wrap a stream in another stream and flatmap it to itself:
// example stream
Stream original=Stream.of("bla").onClose(()->System.out.println("close action"));
// this is the trick
Stream autoClosed=Stream.of(original).flatMap(Function.identity());
//example op
int sum=autoClosed.mapToInt(String::length).sum();
System.out.println(sum);
The reason why it works lies in the flatMap operation:
Each mapped stream is closed after its contents have been placed into this stream.
But the current implementation isn’t as lazy as it should be when using flatMap. This has been fixed in Java 10.
My recommendation is to stay with the try(…) standard solution and document when a returned stream need to be closed. After all, a stream that closes the resource after the terminal operation isn’t safe as there is no guaranty that the client will actually invoke a terminal operation. Changing it’s mind and abandon a stream instant is a valid use, whereas not calling the close() method, when the documentation specifies that it is required, is not.