Method local variables (or simply βlocal variables,β as they are usually called) are distributed across each stack of threads. Variables themselves are not garbage collected. They are automatically restored when the method call ends (usually or abnormally).
Objects are another matter. Objects (including arrays) are usually 1 allocated on the heap, and they are subject to garbage collection.
What about an object (or array) that is allocated by a method and assigned to a local variable?
First of all, the local variable contains a reference to the object. The object is stored on the heap (see above).
When the garbage collector starts (and you usually donβt know when it will be!), It will check for any existing local variables for method calls that are still in process. These variables contain references to objects, these objects are added to the list of objects that need to be saved ... and they are checked for links to other objects, etc.
So, in the end, local variables are automatically destroyed at the end of the method call, but the objects that these variables belong to will continue to exist until the GC (in the end) finds out that they are not available.
1 - Recent JIT compilers Hotspot JITs have an additional optimization called "escape analysis", which is used to search for cases when objects created by a method call can be allocated on the thread stack. This is not enabled by default. If an object is allocated on the stack, it will be restored after the method call is completed. GC is not involved.
2 - You said: "The GC is triggered when the Eden or Long-generation (minor / major GC) blocks are full, etc." This is not necessarily the case. Some of the low pause collectors run before filling in the corresponding spaces. However, this does not change any of the above.
source share