-1

I have a java class which has allocated resources that must be closed. I don't really know how to enforce this, my current approach is implementing the interface AutoCloseable, hoping that the caller calls close() sometimes and adding a boolean closed which is checked at the begin of every method and if true, the method throws IllegalStateException.

Both, that the caller has to call close() and that I have to check closed at the beginning of every method aren't really nice, is there some best practice to avoid this?

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
user3561614
  • 1,024
  • 1
  • 12
  • 20
  • Your question is not clear.Make it clear and share the code snippet. It would help us understand your problem – Sunil Dabburi May 30 '16 at 19:19
  • 1
    "Hoping that"?? Just document your classes so that you basically say that "if you don't close() this class, the behavior is undefined; please use a try-with-resources statement". Job done. – fge May 30 '16 at 19:20
  • The only best practice I can think of is "make sure you do". If somebody using your code doesn't do that, well, that's their problem. The only other thing I'd add is "only close a resource you opened". – Andy Turner May 30 '16 at 19:43

1 Answers1

2

Making your class implement the interface AutoCloseable is good approach in your case, as it allows to use it in a try-with-resource statement.

If for some reason you would like to limit the risk of having instances of your object not properly closed to avoid leaks, you can override the finalize method as next:

@Override
protected void finalize() throws Throwable {
    try {
        this.close();
    } finally {
        super.finalize();
    }
}

WARNING 1: Implementing the finalize method must be done with a lot of caution as it will slow down the work of the GC so you need to ensure that your code will be fast to execute.

WARNING 2: The finalize method is not necessary called so don't rely on it to close your object for you, it only helps to reduce the risk, users of your object still have the responsibility to close it properly.

Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122
  • 1
    Finalizer methods are not guaranteed to be *always* called, so if the resource must really *always* be closed, then this isn't a 100% solution. – Jesper May 30 '16 at 19:38
  • My answer would be: there's no good way to *enforce* this in Java, leave it the responsibility of the user of the class to call the `close()` method. I agree that implementing `AutoCloseable` is a good idea, this should give the user at least a hint that `close()` needs to be called. – Jesper May 30 '16 at 19:46
  • @Jasper I updated my answer to add a warning, please check again – Nicolas Filotto May 30 '16 at 20:15