And as a side note, I did some pretty in-depth research on the topic, and stumbled on this post on the lambda mailing list during Java 8's creation. I am adding it, as it seems to be considering many of the same concerns I have now.
https://mail.openjdk.org/pipermail/lambda-libs-spec-experts/2013-August/002195.html On Sun, Mar 3, 2024 at 10:00 PM David Alayachew <davidalayac...@gmail.com> wrote: > > Hello Amber Dev Team and Core Libs Dev Team, > > I am making my own implementation of java.util.stream.Stream that reads > data from the internet lazily. It's basically > java.nio.file.Files.lines(...), but the file is on the internet instead. > Here is a StackOverflow post I made that basically gave birth to idea. Just > for context. [1] > > I used composition -- I held my resource and the stream inside of my > container data type. However, I also had this container data type implement > java.util.stream.Stream too. This way, the end user can use this object > exactly like a Stream. > > In my implementation, I delegated all method calls to the underlying > stream. But, for each terminal operation, I would wrap the delegated calls > with try-with-resources for my resources, to prevent resource leak upon > exception. > > Now, I know that this is taking an uphill path to a solution. We could > easily tell the user that they have to close the resources themself. Or we > could let the user provide their own resources and thus, leave the > responsibility on their plate. Or we could use the escape-hatch provided by > stream lol, and tell the user to use try-with-resources on my custom > stream. As you all intended us to do, I'm sure. > > I know the reason might seem poorly justified (StackOverflow told me as > much -- [1]), but I did this so that none of the users of my stream would > have to concern themselves doing try-with-resources. Try-with-resources is > an excellent utility, but I have no way to know if I left a resource > unclosed because there are no compiler warnings or errors if I do so. > > Are there any plans to make it easier to detect potential resource leaks? > Ideally with a compiler warning or error? > > Thank you for your time and help! > David Alayachew > > [1] = https://stackoverflow.com/questions/77959436 > >