0

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?

ardayigit
  • 167
  • 2
  • 17
  • 2
    if you add that after the for loop, it can't print the s variable, because it only exists within the for loop. – Stultuske Jul 14 '16 at 10:47
  • 1
    Relax. If the objects (Strings) created from a large heap space are no longer referred to, their memory is eligable to be recycled. When that garbage collection happens is irrelevant, only that it then does not take too much time. Leave it to the automatic garbage collection for best results. – Joop Eggen Jul 14 '16 at 10:51
  • That's what I've learned when I began coding, but here the author of the example says that it's because of the GC and I don't see the link between these two things... – ardayigit Jul 14 '16 at 10:52
  • 1
    If an object becomes unused, unreferred, scans by the garbage collection over groups of objects free up their memory usage. In the above `getName()` could give a new String object, that would come in the "youngest generation" group and be scanned fast. Even the compiler does not need to do something special :(. – Joop Eggen Jul 14 '16 at 10:56
  • 1
    On the other hand `s` is a variable reserved on the stack for function calls. It is a single slot on the stack pointing to the object, despite the loop. Its space is reclaimed when the function returns. Every method call has a fixed size stack usage, calculated by the compiler, and stored in the .class.. This means: just declare inside the loop, as close to its usage; there is no penalty. – Joop Eggen Jul 14 '16 at 11:01

0 Answers0