0

If not, assuming that the close method of this outpustream will fail in the next hour, how should I ensure that the resources are released?

I've read Proper way to close an AutoCloseable, but there is not answer about what try-with-resouces do to enure resouces are released.

Thanks.

goushiso
  • 199
  • 1
  • 10
  • Does this answer your question? [try-with-resources details](https://stackoverflow.com/questions/32423038/try-with-resources-details) – Amongalen Jun 30 '20 at 08:37

1 Answers1

1

Try-with-resouces ensures close() is always called, that's it. It doesn't do anything else with the resource if the close() method throws an exception, because there is nothing else that can be done.

If close() throws exception, you should consider the resource to have been released, but it may have left the resource in an incomplete state. E.g. closing an OutputStream may flush the final buffer, and the writing of that data may fail, leaving the resource (e.g. file) missing the last chunk of data.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Thanks for your answer. please allow me to assume an extreme case to express my concerns clearly. now, there is a computer where a new OutputStream is constantly opened. If these OutputStreams eventually close without throwing any exception, this computer can run indefinitely. But if all OutputStream that has been opened on this computer won't succeed in closing and throw an IOException, will the computer eventually fail to work because there are not enough resources? If try-with-resources is used, is the extreme case possible to happen? Thanks a lot. – goushiso Jun 30 '20 at 08:59
  • @goushiso That has nothing to do with try-with-resources. If `close()` fails, but left the resource open, what could you do to get it closed? Nothing. It doesn't matter *how* `close()` was called, whether directly by you, or by the logic of try-with-resources. The API only provides one method for closing a resource, and if that method fails, there is no alternative. --- However, closing an updated resource implies flushing changes. If the flush fails, the Java APIs will try to close anyway, before throwing the exception caused by the flush. Closing will always attempt to free all resources. – Andreas Jun 30 '20 at 09:07
  • unfortunately there's nothing you can do if `close` fails. And you really shouldn't try to do that. The resource itself implements `Closeable` and only itself can do the best to really release all resources. – Felix Jun 30 '20 at 09:25