0

I was curious about particular test case and wanted to know if even its a realistic scenario.

public void doSomething()
{
    ResultSet rs = null;
    PreparedStatement ps = null;

    try
    {
        ps = conn.createStatement(/* some query */);
        ps.executeUpdate();

        rs = ps.getGeneratedKeys();
        rs.next();

        int temp = rs.getInt(1);
    } catch(Exception e )  {   /* Exception Handlign */}

    finally {
        ps.close();
        rs.close();
    }
}

For the above code, would rs.getInt(1) be threadSafe? I have a single Connection object. The scenario seems highly unlikely to me but I still wanted your opinion.

Thanks

xsami
  • 1,312
  • 16
  • 31
alwaysAStudent
  • 2,110
  • 4
  • 24
  • 47
  • 1
    possible duplicate of [IS ResultSet thread safe](http://stackoverflow.com/questions/2794167/is-resultset-thread-safe) – John Apr 21 '15 at 00:10
  • 2
    What do you mean by "threadsafe"? Where exactly do you have multiple threads in your code? – Thilo Apr 21 '15 at 00:14
  • 1
    The ResultSet in your code is method-local and not leaked. No thread-safety issue can possibly arise. – user207421 Apr 21 '15 at 03:08

1 Answers1

0

By itself, getting values for individual columns is likely thread-safe, since it's read-only. However, the row-to-row navigation is never thread-safe, which (I believe) has more to do with the base ODBC spec upon which JDBC is build upon.

The risk is that one thread could be getting values from a row, and the row is changed, and you have values from 2 or more rows. No way to track this, no way for one thread to be given the row to work on while another thread moves around.

Also, suggest you use try-with-resources, PreparedStatement and ResultSet can throw exceptions upon close, try-with-resources let's you avoid it.

Scott Sosna
  • 1,443
  • 1
  • 8
  • 8