NutchUser
NutchUser

Reputation: 183

Java garbage collector on database connection

A question regarding garbage collector. If i have created database connection and performed some operations on databse and after that i have not used connection object for longer time can garbage collector frees my connection. I want this connection to be used later.

EDIT : just to confirm ,if i have created my connection is at context level of webapp then whats the case ?

Upvotes: 3

Views: 4795

Answers (5)

mprabhat
mprabhat

Reputation: 20323

Depends on what type of reference you have for your connection. If you have strong reference then it wont be garbage collected but if you have weak reference then it will be eligible for GC.

If it is held by a static or instance level, it wont be garbage collected.

But instead of holding to a database connection for long (considering every database has a limit on number of connection) you should release and reacquire as and when needed.

You should also consider using ConnectionPool for better connection management.

Upvotes: 1

Rajesh Pantula
Rajesh Pantula

Reputation: 10241

If you are no longer referencing the connection object, then it is a member for garbage collection, but in no way you can guarantee that it will be garbage collected by gc. it depends entirely on gc.

If you want to use it in future, better make it a global object. so that your application will keep a reference and it will not be a member for garbage collection.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340973

If you keep a strong reference to a Connection object then garbage collector will never touch your object and database connection will remain. Just remember it cannot be used by multiple threads.

On the other hand if you keep opened connection for too long some underlying resources (like TCP/IP socket) might get interrupted.

If you loose the last reference to a connection (by overwriting it or setting to null) garbage collector will release all Java objects associated with the connection and the connection itself. But it will not release the underlying database connection, hence you must always explicitly call:

connection.close();

Upvotes: 9

Will
Will

Reputation: 4713

JVM garbage collection in a nutshell: If you, or anyone else, has a reference to an object then the JVM is not allowed to garbage collect it. If you don't have a reference to it then the JVM doesn't have to garbage collect it until it wants to.

Upvotes: 1

Torben
Torben

Reputation: 3911

The connection will not be garbage collected as long as you keep a reference to it. Theoretically you can therefore keep using it for as long as you like.

Upvotes: 0

Related Questions