views:

88

answers:

1

I am using a class DBConnection which has a static method createConnection.I create a connection object like

Connection con=DBConnection.createConnection();

I don't forget to close it along with statements and resultsets.

Now how different is it having the same DBConnection having a normal method createConnection and create a new Connection object like

DBConnection dbConnection=new DBConnection();
Connection con=dBConnection.createConnection();

and ofcourse I don't forget to close the connections,resultset and statement.

Another doubt is does closing a connection mean making it eligible for garbage collection ie. the con variable will now be equal to null?

+4  A: 

Calling static method on instance (second example) results in exactly the same as calling the static method without having an instance (first example).

Bear in mind that static method DBConnection.createConnection() creates new instance of the connection anyway (this is so called Factory Method), so in your second example you are creating effectively two instances (dbConnection and con).

Closing doesn't make the instances of connections eligible for GC. Closing simply closes underlying physical connection to RDBMS.

pregzt
Actually without knowing the source, there's no way to know if his createConnection() actually creates new connections, returns connections from a pool, returns the same connection with each call, etc.
matt b
The second method calls the non static method of the DBConnection object.What will be the result of the variable of con after closing? Will it be null?
Good point. I'm just assuming that createConnection actually 'creates' connection ;)
pregzt
Yes it just creates connection using the drivers
@Harish: No it will be still the same instance of the connection, but closed. There is not way in java to 'dereference' the object by calling the method on it.
pregzt