Kirk Logan Kirk Logan - 3 years ago 88
Java Question

Java - JDBC Memory Use After Closing All Objects

I am new to Java so go easy on me if this is a silly question.

I just got started with Java a few days ago and the first thing I did was build a helper class for MySQL. I am using

to connect to MySQL and it does so without issue. I also have a helper class to close the
. Here is a snippet of it.


I close each object individually as well as setting them to
once finished.

My concern is that in testing, I use
to test memory use throughout my application and closing the above objects and setting them to
seem to have no bearing whatsoever on the memory usage displayed by
. Here is my code for determining memory usage.

System.out.println("Memory Used: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));

My question is: Why, when I display the memory used while the objects are still in scope as well as at the end of the program the memory appears to never be freed? Is this an issue with the way my objects are being closed, or is the actual memory used not being reflected correctly the way I think it is by

Answer Source

Setting them to null is unnecessary. The garbage collector knows the scope better than you.

You did well to close them all, but they should be done in individually wrapped try/catch blocks. If the first one throws an exception, you'll never close the others that follow.

You are worrying too much about something isn't likely to matter. It's not certain that the JVM will return the freed memory to the OS or that your tools will detect it. The important thing is that the garbage collector is doing its job properly.

This method won't kill memory on its on. You're more likely to find problems elsewhere in your code. Keep profiling with Visual VM to find them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download