The stack can be garbage collected. However, in most JVM implementations it is treated as, for example, a "stack", which by definition excludes garbage collection.
What we call the stack is the accumulation of method activation contexts: for each method called, this is a conceptual structure that contains the method arguments, local variables, a hidden context pointer for the calling method and a slot for save the instruction pointer. The activation context is not available as such from the Java language itself. The context becomes useless when the method exits (using return or due to an exception being thrown). It so happens that when method A calls method B, it is guaranteed that when A regains control, the context of B becomes useless. This means that the context lifetime for B is a sub-range of the context lifetime for A. Therefore, activation contexts (for a given stream) can be allocated using the LIFO ("Last In, First Out") discipline. In simpler words, a stack: a new activation context is placed on top of the context stack, and the first context will be deleted.
In practice, activation contexts (also called stack frames) are concatenated in stack order in the selected area. This area is obtained from the operating system when the thread starts, and the operating system returns it when the thread terminates. The top of the stack is indicated by a specific pointer, which is often contained in the CPU register (this depends on whether the JVM interprets or compiles the code). The "caller context pointer" is virtual; the caller context is necessarily located just below in stack order. GC does not intervene: the stack area is created and regenerated synchronously, from the activity of the stream itself. It also works in many languages, such as C , which do not have a GC at all.
Now, nothing prevents the implementation of the JVM otherwise, for example. highlighting activation contexts on the heap and collecting them with GC. This is usually not done in Java virtual machines, since stack allocation is faster. But some other languages ​​should do such things, especially those that play with continuations , still using the GC (like Scheme and its call-with-current-continuation ), because such games violate the LIFO rule above.
Thomas Pornin Mar 16 '10 at 11:38 2010-03-16 11:38
source share