1

Saying I have an autocloseable resource (returned by a Sql.query call), then is it mandatory to put its return into a variable and try-with-resource it to avoid resource leaking?

    try (final Sql sql = ...) {
            // sql.query instanciates a java.sql.ResultSet and returns it
            sql.query("SET @x := 1");
    }

In such case, is it mandatory to change this code to:

    try (final Sql sql = ...) {
            // sql.query instanciates a java.sql.ResultSet and returns it
            try (final ResultSet useless = sql.query("SET @x := 1")) {}
    }

To avoid having a non-closed java.sql.ResultSet? I find no clear documentation about that case... I guess it should be, but I find no clear documentation about it (and since it feels strangely heavy, I'm not sure it's actually required)

Xenos
  • 3,351
  • 2
  • 27
  • 50
  • Yes. Otherwise it is possible that your cursors may remain open on the database, and you'll eventually run out of connections. – Elliott Frisch Mar 21 '18 at 10:12
  • Ok, I had a doubt since IntelliJ reports a `try (final ResultSet useless = sql.query("SET @x := 1")) {}` as having an unused variable and an empty `try` block (which should then be just a hint and not a warning) – Xenos Mar 21 '18 at 10:16
  • @Xenos False positive. – lexicore Mar 21 '18 at 10:29
  • @lexicore Alright, then I'll try these things even if the try block is empty, and put on a `SuppressWarning` on the 'false positives' about "empty try block" – Xenos Mar 21 '18 at 10:46
  • @Xenos Also add a comment in the empty try block to explain why it is empty. – lexicore Mar 21 '18 at 10:47
  • No, it isn't mandatory that you close that particular way, but it is mandatory that you close it somehow, and auto-close/try-with-resources is the most foolproof way. – user207421 Mar 21 '18 at 11:31

0 Answers0