0

I've been searching how to raise a warning in Java if a specific object from a class that has a close() function in it doesn't at some point call that close() function (as for example for the BufferedReader class).

In searching through this, I found the Closeable and AutoCloseable interfaces and how they work, as well as this questionn that helped a lot : Force warning when class is not closed

But I still face the issue that when the object in question is created through a function, it is not supposed that it hasn't been closed.

For instance, in this code :

//X.java
import java.io.Closeable;
import java.io.IOException;

public class X implements Closeable{

    @Override
    public void close() throws IOException {
        System.out.println("CLOSE");
    }
}
//Main.java
public static void main(String[] args) throws IOException {
    X x = new X();
    System.out.println(x);
}

A ressource leak warning is raised, but in this one (same X.java) :

//Main.java
public class Main {
    public static void main(String[] args) {
        X x = getX();
        System.out.println(x);
    }

    public static X getX(){
        return new X();
    }
}

No warning is raised where I want one to be.

Thanks !

r.jaoui
  • 31
  • 3
  • Finalizers? https://en.m.wikipedia.org/wiki/Finalizer – Benjamin Gruenbaum Apr 10 '21 at 09:19
  • Isn't the finalizer the function that is runs when the GC deallocates the ressources (that is to say, whenever it wants to/can) ? Because it was my first option but since I have to close big chunks of data (hundreds of Mbs to Gbs worth) this led to a LOT of memory being used up, which isn't an option... I need the close() function I think, since there is no way to force Object finalization. – r.jaoui Apr 11 '21 at 19:43

0 Answers0