Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of close() and = null for Closable objects

Tags:

java

Say, I'm using connection to database named con (or socket or anything else which is Closable). What happens after close()? Does con become equal to null or there is still something in it? And what is the difference between con.close() and con = null?

like image 821
Mr Scapegrace Avatar asked May 27 '15 22:05

Mr Scapegrace


People also ask

Can we store null in object?

The reference variables will store null if they are explicitly referencing an object in memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value.

Can we call method with null object?

But just to make it clear - no, you can't call an instance method with a null pointer.


1 Answers

When you call close, the object should free all the resources it uses behind the scenes. In case of an instance of java.sql.Connection, it will one of two things:

  • Free any physical connection to the database, thus freeing resources. This happens when you open a database connection manually e.g. DriverManager.getConnection(...).
  • Go into a SLEEPING state and wait to be invoked again. This happens when the Connection is handled by a DataSource which is handled by a database connection pool.

Setting the object con = null just assigns null value to a variable, the reference will still be alive until the Garbage Collector decides to remove it. Still, setting the Connection to null doesn't call close method, thus you can have memory leaks.

As a best practice, you should ALWAYS call close method on instances of Closeable or use try-with-resources (available since Java 7) to make sure the resource(s) is(are) always closed.

like image 87
Luiggi Mendoza Avatar answered Nov 09 '22 16:11

Luiggi Mendoza