Andre
Andre

Reputation: 51

Connection close

Have a method getConnection() to initialize a connection. I know, that I can use

try (Connection conn = getConnection()) {
    ...
    Target t = new Target(conn);
    ...
}

in Java 7 to work with that connection and automatically close it at the end of the try. But what happens if I just use the following code without a try:

Target t = new Target(getConnection());

Does that create a resource leak because I can not close the connection because I have do not hava a variable for the connection?

Upvotes: 3

Views: 125

Answers (2)

Debapriya Biswas
Debapriya Biswas

Reputation: 1339

Yes you are correct , it will create resource leak . The Connection interface in java extends AutoCloseable interface which says "A resource that must be closed when it is no longer needed." So you have to explicitly close the connection after you are done in your code (or use try with resources which does for free) .

Be aware n your case in the try with resource block you are passing Target t = new Target(conn); there are slim changes of memory leak not connection leak .

Upvotes: 0

Mark Rotteveel
Mark Rotteveel

Reputation: 108941

If you use the code without try-with-resources (or an old-school try-finally with an explicit close), then - obviously - the connection will not be closed by the code shown. So unless Target somehow closes the connection, you will have a resource leak in that situation.

Be aware that even when using try-with-resources, you may still have a memory leak, even when the connection gets closed. This can happen if the connection is held in an instance field of Target, and target lives longer than the try-with-resources block, because in that case the connection (and any other objects held by the connection) cannot be reclaimed by the garbage collector until target itself becomes eligible for garbage collection.

As a general rule of thumb for resource management, whoever create a resources is also responsible for closing that resource (unless explicitly documented otherwise), so unless you have a very good reason not to, you should be using try-with-resources here.

Upvotes: 2

Related Questions