Java / Lombok Interview questions
What is @Cleanup used for?
@Cleanup automatically calls a resource's close() method (or another method you
specify) at the end of the enclosing block, functioning as a Lombok-era predecessor to Java's built-in
try-with-resources for ensuring resources get released.
@Cleanup InputStream in = new FileInputStream("data.txt"); // Lombok inserts a finally block that calls in.close() at the end of this scope
Since Java 7 introduced try-with-resources as a language feature, @Cleanup is largely
historical for closing standard AutoCloseable resources — most modern code reaches for
try-with-resources directly instead. It remains occasionally useful for calling a cleanup method that isn't
named close(), via @Cleanup("customMethodName"), which try-with-resources can't
directly express.
More Related questions...