I have a piece of code that load a very big image in memory. So it seemed like a reasonable thing to call
System.gc();
before loading the
Did you get any performance improvements with the System.gc()? I don't think so, since you probably dont have a lot of objects that needs to be collected before you load the image.
Usually modern garbage collectors know best when to run, so you shouldnt force a collection, unless you have a really really good reason to. (for example a benchmarking application as suggested by that plugin)
btw: Calling System.gc() recommends the VM to perform a "full" or "large" collection, which means that all threads are stopped shortly. Otherwise it will probably only make "small" garbage collections, which don't stop all threads.
Run your program with -verbose:gc to see how many bytes are collected.
There is also lots of technical information on garbage collection here: http://java.sun.com/developer/technicalArticles/Programming/GCPortal/
It's fine to call the garbage collector, you don't get any "problems" from it. However, I doubt it will significently boost performance, unless that call also deals with defragging the allocated data. I don't know that.
What you should do in this case is profile the code. Run it several times, see what sort of results you get.
Typically the GC is smarter than you, so it's better to let it run whenever the runtime decides. If the runtime needs memory, it'll run the GC itself
Ensure that the large objects can be gc'ed as early as possible. I.e. set variables to null and/or let them fall out of scope. THis helps!
You already got plenty of good advice, which I will try not to reiterate.
If you actually get problems with the GC, like full stops of your application for a second, do the following: 1. check that there aren't any calls to System.gc(); 2. check out the various options for configuring the gc. There are tons of those around, and they are much more helpful, then forcing gc.
If a memory allocation fails, a GC cycle is initiated and the allocation is tried again.