5
votes

Hi all I knew it is a old question but just curious today. As we know connection.close will also close preparedStatement(correct me if I am wrong). but what if I close connection then close preparedStatement

conn.close();
ps.close();

Will I get a nullpointer exception?

Someone was saying depends on your jvm speed.sometimes ps.close() will run ahead and close first before conn.close finish his job and so you wont get nullpointer.

In order to test that, I have modified the code

conn.close();
Thread.sleep(5000);//I give 5s to conn.close to finish his work. should be enough
ps.close();

But I didn't get the nullpointer.

So my question is what happened here if i close conn first and then ps.

thanks all.

2
Why would you get a null pointer exception? What variable has become null? However you should certainly close resources in the reverse order of acquisition, in this case the PreparedStatement before the Connection (and the ResultSet before the PreparedStatement). - user207421

2 Answers

5
votes

The JavaDoc for Statement.close() states:

Calling the method close on a Statement object that is already closed has no effect.

I would suggest that means an implementation ought to throw no exceptions if your statement has already been closed by a call to Connection.close().

1
votes

As per the javadoc of Statement Interface

close
void close()
           throws SQLExceptionReleases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources. 
**Calling the method close on a Statement object that is already closed has no effect.** 

So there won't be any problem if you close an already closed Statement.