Hacker News new | past | comments | ask | show | jobs | submit login

That BufferedReader constructors is not supposed to throw, unless the reader is null or you're out of memory. If your out of memory you should probably abort the program execution because the difficulty of correctly recovering from an OOM exception is between hard and impossible.

Edit: Disregard the above, it was too naive.

It cannot leak because of a stronger warranty. In the JLS, it is specified that the try-with-resources track successfull initialisation of AutoClosable resources, not successful assignation. So one try with resources can desugar into the logical equivalent of multiple nested try-catch-finally !






> difficulty of correctly recovering from an OOM exception is between hard and impossible.

In Java out of memory is signaled with an OutOfMemoryError which is a throwable (and can be caught) but is not technically an exception. Errors should generally never be caught and cannot be recovered from, which is how they differ from exceptions.


It's not great, but you can always catch and retry if your belief is that the GC will free enough memory to allow the attempt to continue after the memory pressure subsides.

Let's say you get 1/100 requests that are randomly sent to your process. That 1 takes 100x the average memory usage of the others. You could spin it out to different services to better handle the weird one-off, but that doesn't always make sense. Sometimes you just need to be ok with working the 100x job and let the other 99 get progressive falloff retry. Different solutions are always possible.


It's possible to recover enough to cleanly save the user work and shutdown. You have to mesure of much memory you need for a clean shutdown and allocate a byte[sizeForShutdown] at the start of the application in the top level exception handler (the only one that should catch that error) and free that byte array before doing anything else.

Now you can argue that this is not truly recovering from exception but it is a lot better than what you can do with most of the other Error subclasses. I said most because there are easy to recover from Error like the StackOverflowError where you just have to fail the operation or request that caused the error.


Does the JLS actually guarantee that if you free that byte array then the extra memory will be immediately available? I thought there could potentially be some lag. The safer approach would be to create all of the objects you need for a clean shutdown during program launch and keep them around. Then you won't need to allocate any memory in the exception handler.



Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: