如果所有调用者都确保关闭它,我是否需要在准备好的语句创建上使用 try-with-resource?

Do I need a try-with-resource on prepared statement creation if all callers make sure to close it?

我正在处理一些遗留代码,它看起来像这样:

    PreparedStatement prepared_statement;
    if (x > 0) {
        prepared_statement = connect.prepareStatement(sql_query);
        prepared_statement.setInt(1, id);

        for (int i = 0; i < list_size; i++) {
            String internal_token_symbol = callMethod(coin, exchange_list.get(i));
        }
    } else {
        prepared_statement = connect.prepareStatement(sql_query);
        prepared_statement.setInt(1, token_id);
    }

    return prepared_statement;

这里的关键是它创建了一个准备好的语句,然后 returns 它稍后使用。请注意,如果发生异常,它不会使用 try-with-resource 或关闭。

我的问题是,如果此方法的 每个 调用者都使用 try-with-resource,是否存在无法关闭语句的危险?例如如果所有来电者都这样做:

try (PreparedStatement ps = resultOfCallingMyMethod()) {
   // Use the prepared statement
}

我自己通过这样做证明了这一点:

@Test
public void testIPrint() throws IOException { // this prints
    try (MyCloseable closeable = new MyCloseable()) {

    }
}

@Test
public void testIAlsoPrint() throws IOException, InterruptedException { //this doesn't print :(
    try (MyCloseable closeable = iThrowAnException()) {

    }
}

private MyCloseable iThrowAnException() {
    MyCloseable closeable = new MyCloseable();
    if (true) {
        throw new RuntimeException();
    }
    return closeable;
}

public static class MyCloseable implements Closeable {
    @Override
    public void close() throws IOException {
        System.out.println("I was closed!");
    }
}

不,没关系,唯一的问题是:如何确保每个调用者都在使用try-with-resource?

通常情况下,我尽量不将 PreparedStatement 泄露到 class 之外。这样,关闭它仍然是 class 的责任。

编辑: 实际上,按照 Mike Strobel 的评论:如果 x > 0callMethod 抛出异常,它不会返回给调用者并且不会关闭。