Heap and Stack memory in Java
Heap is used by the Java Runtime to allocate memory for objects and classes. The creation of a new object also happens on the heap. This is also the domain of the garbage collector. Any object created on the heap has global access and can be referenced from anywhere in the application.
Stack is a data storage area also located in shared random access memory (RAM). Whenever a method is called, a new block is created in stack memory that contains primitives and references to other objects in the method. As soon as the method finishes working, the block is also no longer used, thereby providing access to the next method. The size of stack memory is much smaller than the amount of memory on the heap. The stack in Java works according to the LIFO scheme (Last-In-First-Out)
Differences between Heap and Stack memory:
- The heap is used by all parts of the application while the stack is used by only one thread of program execution.
- Whenever an object is created, it is always stored on the heap, and the stack memory contains only a reference to it. The stack memory contains only local variables of primitive types and references to objects on the heap.
- Objects on the heap are accessible from anywhere in the program, while the stack memory cannot be accessed by other threads.
- The stack memory exists only for a while, while the memory in the heap lives from the very beginning until the end of the program.
- If the stack memory is completely occupied, then the Java Runtime throws a java.lang.StackOverflowError exception. If the heap memory is full, then a java.lang.OutOfMemoryError: Java Heap Space exception is thrown.
- The stack memory size is much smaller than the heap memory.
- Because of the simplicity of memory allocation, stack memory is much faster than heap memory.
The -Xms and -Xmx JVM options are used to determine the initial and maximum size of memory on the heap. The memory size for the stack can be determined using the -Xss option.
Is it true that primitive data types are always stored on the stack and instances of reference data types are always stored on the heap?
Not really. The primitive field of a class instance is not stored on the stack, but on the heap. Any object (everything that is explicitly or implicitly created using the new operator) is stored on the heap.
How are variables passed to methods, by value or by reference?
In Java, parameters are always passed by value only, which is defined as "copy value and pass a copy". With primitives, this will be a copy of the content. With links - also a copy of the content, i.e. copy of the link. At the same time, it is possible to change the internal members of reference types through such a copy, but the link itself pointing to the instance is not.
Read also:
- Types of classes in Java. Nested classes
- Usage of assert statement in Java
- Nested classes, local, anonymous in Java
Comments
Post a Comment