Question

Every time when I initiate a list in java, I will do

List<Integer> list = new LinkedList<>();

I assume that this will allocate the list on heap. Wonder if there's anyway that I could allocate the list on stack?

Was it helpful?

Solution

All objects, including their individual attributes, are stored on the heap.

All local variables, and their arguments, are stored on the stack because they contain primitive values or references.

However, in special cases, the java virtual machine may perform escape analysis and decide to allocate objects (including your LinkedList) on a stack, but this normally doesn't happen and isn't a major concern.

As a general rule, if you allocate an object on a stack you will get a copy of the object when you call a function that refers to it. In contrast, if you allocate an object on the heap, when you pass the pointer to the object you will get a copy of the pointer (which points to the very same object on the heap.)

OTHER TIPS

It is theoretically possible for JVM implementations to allocate objects on the stack, using "escape analysis." If it can be determined that a reference to a created object never leaks off the stack, a JVM could allocate it on the stack instead of the heap. The benefit of this would be to reduce garbage collection overhead; when the stack frame is exited, that memory could be immediately reclaimed. It might also boost speed because of the locality of reference.

Starting in Java 7, escape analysis was introduced in the Oracle's HotSpot Java runtime. With this enhancement, HotSpot may choose not to allocate stack-local objects that aren't modified; rather than allocating them on the stack, it deletes the allocation altogether. While this stops short of stack allocation, it does demonstrate that such things are permissible runtime optimizations.

There is no way for the Java programmer to directly control this behavior, however. It's an optimization performed by the JIT compiler. I'm not sure if the language specification would permit this sort of optimization at compile-time. It might, but I haven't studied it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top