aspose file tools*
The moose likes JDBC and the fly likes Connection object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Connection object" Watch "Connection object" New topic
Author

Connection object

Vetrik Kumaran
Greenhorn

Joined: Jul 01, 2003
Posts: 7
Hi,

See the following code, my question is can i assign null after closing the connection object or is it not the standard.

Connection conn = DriverManager.getConnection("url","user","pwd");

.
.
.

if(conn != null{

conn.close();
conn = null;

}

:-)




Try Try Try...
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
Originally posted by Vetrik Kumaran:
Hi,

See the following code, my question is can i assign null after closing the connection object or is it not the standard.


Yes, you can do that, it's harmless because you're done with the connection and closing it closes all the child resources it owns, but off the top of my head I can't think of a good reason to actually do so in good code. The only thing I think that does is make the object eligible for garbage collection a few nanoseconds earlier, but perhaps I'm missing something...
Vetrik Kumaran
Greenhorn

Joined: Jul 01, 2003
Posts: 7
I think even the close() will enable the garbage collection, correct me if I am wrong.

Babji Reddy
Ranch Hand

Joined: Jan 24, 2006
Posts: 106
close() will not make the connection eligible for GC. It just releases JDBC resources that are used by that connection.

As you know the connection is an interface thats implemented by a db vendor.
so its like
VendorConnection implements connection{
...
close()
{
this = null ; // NOT POSSIBLE. RIGHT!! .. SO JUST close() cannot make it eligible for GC
}
}
stu derby
Ranch Hand

Joined: Dec 15, 2005
Posts: 333
Originally posted by Babji Reddy:
close() will not make the connection eligible for GC. It just releases JDBC resources that are used by that connection.


Right.

To be clear for the questioner: just like elsewhere in Java, an object becomes eligible for GC when and only when there are no more references to it (we'll ignore weak references since they sort of don't count for GC purposes). In well-designed code, stale objects go out of local scope quickly and then become eligible for GC; in poorly designed code, objects can have global scope and hacks like setting things null get used to compensate for the poor design.

A common poor coding practice is to have a Connection member variable in the class because the programmer is too lazy to type a new local variable in each method that uses a connection briefly. Then for long-lived class objects, it becomes necessary to junk up the code with "conn = null" to force appropriate short-lived behaviour on the connection objects.
 
 
subject: Connection object