I have some difficulties to understand how does the garbage collector (GC) operated. What I've understood is that when an object "looses" its references, the GC destroys it to free the memory. I've also read that nobody knows when it will run, but then, what must we do the free memory when we have to code a program that uses a lot of memory? Is it a good idea to force the garbage collection, or is there always a good manner to code that avoids calls to the GC? Is there any way to "test" if the GC took effect, without having an influence on its operation? I've found in another post the following example to show the action of the GC:
for (File f : files) {
String s = f.getName();
}
The author of the post says that after each iteration, the variable "s" is not used anymore, so it is considered as "garbage". But if I add something like System.out.println(s)
after the for-loop, the "last" variable s will still be used, but the compiler doesn't allow us to compile this code, so that has nothing to do with the GC... Is there any problem in my understanding?
A last question: is that the GC that thanks to the GC that we don't use destructor in Java?