Sobes.tech
Junior — Middle

What parameters and properties should resources have to be automatically released or closed?

sobes.tech AI

Answer from AI

In Java, for automatic resource release or closure, a class must implement the AutoCloseable or Closeable interface. This allows the resource to be used in a try-with-resources statement, which guarantees the invocation of the close() method after the resource is no longer needed, even if an exception occurs.

Main requirements:

  • Implementation of the close() method, which releases the resource.
  • No need to explicitly call close() — this is handled by try-with-resources.

Example:

class MyResource implements AutoCloseable {
    public void doSomething() {
        System.out.println("Working with resource");
    }
    @Override
    public void close() {
        System.out.println("Resource closed");
    }
}

public class Main {
    public static void main(String[] args) {
        try (MyResource res = new MyResource()) {
            res.doSomething();
        } // res.close() is automatically called here
    }
}