Sunday, May 23, 2021

Java: Handle Custom Resource Using try-with-resources

  • To construct a custom resource that will be correctly handled by a try-with-resources block, the class should implement the Closeable or AutoCloseable interfaces, and override the close method
  • Closeable extends AutoCloseable
  • Closeable extends IOException whereas AutoCloseable extends Exception
  • Closeable interface is idempotent (calling close() method more than once does not have any side effects) whereas AutoCloseable does not provide this feature
  • Resources that were defined/acquired first will be closed last
  • A try-with-resources block can still have the catch and finally blocks – which will work in the same way as with a traditional try block
  • Finally block will be executed once all the declared resources have been closed
  • After Java 9, we can now use final or even effectively final variables inside a try-with-resources block; earlier only fresh/new variables were used

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...