views:

182

answers:

5

It is necessary to disconnect from the database after the job is done in Java? If it is not disconnected, will it lead to memory leaks?

+5  A: 

You must always close all your Connections, Statements and ResultSets.

If not, is more probable you can't obtain new connections from the pool than a memory leak.

Sinuhe
A: 

I don't have a source, but I believe (if I remember right, it's been a while since I've touched JDBC) that it depends on the JDBC driver implementation. You should always close your connections and clean up after yourself as not all JDBC drivers do it for you (although some might).

This goes back to a rule that I like to follow - If I create or open something, I'm responsible for deleting or closing it.

Thomas Owens
+2  A: 

You should provide more details like which framework you are using or something.

Anyway, are you using JDBC? If so you should close the following objects by using their respective close() methods: Statement, ResultSet and Connection.

NickDK
+2  A: 

Assuming you are using JDBC, the answer is yes. If you don't close the connection, then the JDBC driver might try to close it in a finallizer, but that could hold the connection open for a very long time, causing resource issues (the amount of database connections allowed to be open at one time is finite). Typically JDBC programming is done with a database pool, and not closing the connection will mean that the pool will run out of available connections very quickly.

Some application servers (e.g. JBoss) will detect when a connection wasn't closed and close it for you if it is managing the transactions, but you should not rely on that.

Of course some JDBC drivers are not pure java drivers, at which point memory leaks become a very real possibility.

Yishai
A: 

yes and yes

OscarRyz