Fundamentals 9 min read

Special Cases in Java Resource Closing: Utilities, Return Patterns, Non‑Closeable Streams, Nested Streams, JDBC Statements, and Sockets

This article, the fifth in a static code scanning series, explains six special scenarios—custom close utilities, methods returning resources, streams that need not be closed, nested stream closures, JDBC statement/result set relationships, and socket streams—that complicate determining whether Java resources have been properly closed.

360 Quality & Efficiency
360 Quality & Efficiency
360 Quality & Efficiency
Special Cases in Java Resource Closing: Utilities, Return Patterns, Non‑Closeable Streams, Nested Streams, JDBC Statements, and Sockets

This article, the fifth in a series on static code scanning, discusses special scenarios that complicate determining whether a Java resource has been properly closed.

1. Custom utility classes (e.g., QHRecyleUtils) used to close resources require the scanner to trace into the utility method to verify the actual close operation.

/**
 * Resource recycling utility class
 */
public final class QHRecyleUtils {
    public static void close(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) { }
        }
    }
    public static void close(OutputStream outputStream) {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) { }
        }
    }
    // ... other overloads for Reader, Writer, etc.
}
public void test_01() {
    FileOutputStream fos;
    OutputStreamWriter osw = null;
    try {
        fos = new FileOutputStream("e:/a.txt");
        osw = new OutputStreamWriter(fos, "UTF-8");
        osw.append("55555");
    } catch (Exception e) {
        // handle
    } finally {
        QHRecyleUtils.close(osw);
    }
}

2. When a method returns a resource object, the method itself should not close the resource; the caller is responsible.

private static InputStream getNewInputStream() throws IOException {
    InputStream in = null;
    try {
        in = new URL("http://www.so.com").openStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return in;
}

3. Certain streams such as ByteArrayInputStream, ByteArrayOutputStream, StringWriter, etc., do not need to be closed because their close() methods have no effect.

4. For nested streams, only the outermost stream needs to be closed; closing it cascades to the inner streams.

FileOutputStream fileOutputStream = new FileOutputStream("A.txt");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
DataOutputStream out = new DataOutputStream(bufferedOutputStream);
// Closing out will also close bufferedOutputStream and fileOutputStream
out.close();
/**
 * Closes this output stream and releases any system resources
 * associated with the stream.
 */
public void close() throws IOException {
    try { flush(); } catch (IOException ignored) { }
    out.close();
}

5. Closing a JDBC Statement automatically closes any ResultSet created by that Statement.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// When stmt.close() is called, rs is also closed
stmt.close();

6. Streams obtained from a Socket are closed automatically when the socket is closed; closing the stream also closes the socket.

Socket socket = new Socket("127.0.0.1", 8001);
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
// Closing the socket closes both streams
socket.close();

The article concludes that handling these six special cases makes accurate resource‑close detection complex, but the author's static analysis tool (Fireline) can cover most scenarios with low false‑positive rates.

Javaresource managementbest practicesstatic-code-analysisJDBCio-streamscloseable
360 Quality & Efficiency
Written by

360 Quality & Efficiency

360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.