0

In java, is it necessary for me to manually close all AutoCloseable and Closeable objects (whether through explicit call or relying on try-with-resources)?

Does the JVM not automatically clean up AutoCloseables and Closeables when they are no longer being referenced?

Is calling close explicitly (whether through explicit call or relying on try-with-resources) a manner of etiquette (i.e., recommended but not necessary) and is the reason to avoid indeterministic resource deallocation which would happen otherwise if one relied on the built in GC?

morpheus
  • 18,676
  • 24
  • 96
  • 159
  • GC is not able to release anything other than allocated memory. Resources, however, are not limited to allocated memory. – PM 77-1 Jun 11 '16 at 20:21
  • 1
    The primary reason is that you close it in a timely fashion (eg finalizer can take a while to run (if ever), and ensure it is closed even if the object itself is long-lived. Or with JDBC + a connection pool: to ensure that the connection is returned to the pool. – Mark Rotteveel Jun 11 '16 at 20:21

0 Answers0