Interface java.lang.AutoCloseable

A class implementing this interface can be used within a "try-with-resources" statement. Its "close" method will be called automatically, when the "try" block is finished, whether it finished normally or threw an exception.

Here is how you can use it on your own class:

public class MyAutoCloseable implements AutoCloseable {

  @Override
  public void close() {
    System.out.println("Closing");
  }

}

This is how you call it:

try (MyAutoCloseable a = new MyAutoCloseable()) {
}  // will print "Closing" on standard output

Usage in Java SE API

Java interfaces extending this interface:

  • "Closeable" from "java.io" and its many subinterfaces
  • "ObjectInput" and "ObjectOutput" from "java.io"
  • "Closeable" from "java.io"
  • "FileLock" from "java.nio.channels"
  • "Connection", "Statement" and "ResultSet" from "java.sql" and their subinterfaces: "PreparedStatement", "CallableStatement"; "RowSet", "CachedRowSet", "WebRowSet", "FilteredRowSet", "JoinRowSet", "JdbcRowSet", "SyncResolver"
  • "Line" from "javax.sound.sampled" and its subinterfaces "DataLine", "SourceDataLine", "TargetDataLine", "Clip", "Mixer", "Port"
  • "Transmitter", "Receiver" and "MidiDevice" from "javax.sound.midi" and their subinterfaces "MidiDeviceTransmitter"; "MidiDeviceReceiver"; "Sequencer", "Synthesizer"

Java classes implementing this interface:

  • "Closeable" from "java.io" and many classes implementing it
  • "XMLEncoder" and "XMLDecoder" from "java.beans"
  • "ObjectInputStream" and "ObjectOutputStream" from "java.io"

viliam@bur.sk