In this post under Lombok, I will explain with example the purpose of “@Cleanup” annotation.
In Java whenever we open a resource, we have to close it after we are done with the resource.
Usually all resource will have “close” method. We call that “close” method to close the resource.
To do this in Java, earlier we used to take help of try and finally block as shown below
try {
//open the resource
} catch(Exception exception) {
} finally {
//close the resource
}
If we forget to close the resources, it would lead to problems. So closing the resources was very important.
Then Java, came up with short form of try and finally block in which the resources (that are opened) are automatically closed by JVM by calling the “close” method on the resource.
The short form frees developers from closing the resource.
So even if we forget to close a resource, it won’t lead to problems, as JVM will take care of closing the resources.
The short form is as shown below
try(/*open a resource*/) {
}
The only condition was that the resources must implement “AutoClosable” interface, which has “close” method.
Lombok went ahead and replaced the above try block with an annotation “@Cleanup”
Once you annotate a resource with “@Cleanup” annotation, the resource is automatically closed and you don’t need try block shown previously.
Below is the main code for your reference.
Main class
1 package package24;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.FileWriter;
8 import java.io.IOException;
9
10 import lombok.Cleanup;
11
12 public class Example24 {
13 public static void main(String[] args) throws IOException {
14 File inputFile = new File("input.txt");
15 File outputFile = new File("output.txt");
16 FileReader fr = new FileReader(inputFile);
17 @Cleanup BufferedReader br = new BufferedReader(fr);
18 FileWriter fw = new FileWriter(outputFile);
19 @Cleanup BufferedWriter bw = new BufferedWriter(fw);
20
21 String data = br.readLine();
22 while(data != null) {
23 bw.write(data);
24 bw.write("\n");
25 data = br.readLine();
26 }
27 }
28 }
As you can see in the above main code, at line 17, we declared and created a “BufferedReader” resource and we annotate it with “@Cleanup” annotation.
Similarly at line 19, we declared and created a “BufferedWriter” resource and we annotate it with “@Cleanup” annotation.
As a result of which, when the code finishes execution, the two resources are automatically closed.
In this way we can use lombok provided “@Cleanup” annotation