Class CloseableURLConnection

java.lang.Object
java.net.URLConnection
org.apache.tomcat.util.buf.CloseableURLConnection
All Implemented Interfaces:
AutoCloseable

public final class CloseableURLConnection extends URLConnection implements AutoCloseable
AutoCloseable wrapper for URLConnection that ensures all resources are released on close.

Different URLConnection subclasses require different cleanup:

  • HttpURLConnection (including HttpsURLConnection) requires disconnect() to release the underlying socket.
  • JarURLConnection requires its resources to be released. When the stock JDK handler is used with setUseCaches(false), getJarFile() returns a JarFile private to this connection, which is closed directly. Otherwise the JarFile may be shared - the JDK caches one instance while caches are enabled, and a custom jar handler (such as nested JAR support) may share one regardless of the use of caches - so only the input stream is closed, leaving any shared JarFile open for its other users.
  • Other URLConnection types only require any obtained streams to be closed.

This wrapper sets setUseCaches(false) on the wrapped connection, tracks whether getInputStream() was called, and performs the appropriate cleanup in close().