Project Lombok - Automatic Resource Management using @Cleanup


We can use Project Lombok provided a @Cleanup annotation to ensure a given resource is automatically cleaned up before the code execution path exits your current scope.
When we use a resource like BufferedReader, FileReader, InputStream, OutputStream in Java, we should remember to close that resource after using it.

Without Project Lombok

Before Java 7, we can close a resource in a finally block as below:
package net.javaguides.lombok.cleanup;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader("sample.txt");
            br = new BufferedReader(fr);
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fr != null) {
                fr.close();
            }

            if (br != null) {
                br.close();
            }
        }
    }
}
Since Java 7, we can use the try with a resource to close the resource automatically as below:
package net.javaguides.lombok.cleanup;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        try (FileReader fr = new FileReader("sample.txt");) {
            BufferedReader br = new BufferedReader(fr);
            String sCurrentLine;

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        }
    }
}
Using try with a resource, Java will invoke the method close() of the resource after using automatically.

With Project Lombok

With Project Lombok, we have another alternative way to close a resource automatically by using @Cleanup annotation:
package net.javaguides.lombok.cleanup;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import lombok.Cleanup;

public class BufferedReaderLombokExample {
    public static void main(String[] args) throws IOException {
        @Cleanup
        FileReader fr = new FileReader("sample.txt");

        @Cleanup
        BufferedReader br = new BufferedReader(fr);
        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }
    }
}

Reference

GitHub Repository

You can view the source code of this article on my GitHub repository at https://github.com/RameshMF/project-lombok-tutorial

Comments