Stack And Heap in Java

Luyen Ninh
Culi Tech Viet
Published in
6 min readAug 3, 2019

In the article I’ll clarify the difference Stack and Heap in Java. How do it work in memory. I think it really important for all Java professional to understand. When you know how do it work, we can avoid write some code which could crash application with memory error. Okay ! Please take your coffee cup away.

Photo by Luis Villasmil on Unsplash

1. What is stack and heap in memory ?

When our application running, they need access to some of our device’s memory(RAM). For example when we create a variable, object and hold it on the memory. This memory split to two sections the stack and the heap.

2. The Stack how do it work ?

The stack used widely, But there isn’t a single stack. Which created for each thread. Whenever we create a new thread, the JVM(Java visual machine) will be allocated a stack for this on the memory. In other words, every thread has its own stack. The process allocated stack on memory is dealt with when the program is compile.

//image multi thread and multi stack

Mechanism put data on stack is FILO(First In Last Out) data structure. We add data to the stack by pushing it to the top. And the new item goes on to the top. When the stack want to be freed, the item on top(that is the last item to be added) always is first item removed.

But when is stack want to be freed ?
In the function when compiler run to statement “return xxx” then all variable have declared before will be remove from the stack. And If the method without return then all variable have declared before will be remove from the stack when compiler run to the last curly brackets of method. In another words, when thread is completed then our stack would now be empty.

// animation add and remove items in stack.

3. The Heap how do it work ?

The Heap allows us to store data that has long lifetime than a single code block or function. For example object which is shared across multiple methods. You can think of the heap as being a huge area for storing data. Actually, you can think of the heap as being all the memory of your application except for the data on the stacks.

In an application there is one heap which is shared across all the threads

In Java, all objects are stored on the heap. So the stack is used for local primitive variables such as int, double, long but all objects such as String, Customer, or Integer Object will be stored on the heap. For the objects on the heap there’ll be a pointer to the object which is the variable reference stored on the stack.

For example :

In the stack , variable “name” is the variable that contains the memory address reference to where in the heap this object lives.

  • The Objects are stored on the heap.
  • Variable are a reference to the object
  • As a local variable will be stored on the stack.

Above this is simple example when we declare variable in java. What happen when we pass data through argument, declare and modify data in collections (List, HashMap ) in java ?

4. Value, references and escaping references.

  • With primitive data ?

The all variable above will be storage on the stack(the right rectangle). At the first line in the main method. The variable localValue will be storage on the stack. When the compiler run to calculate method, in the argument we create a variable is calcValue and assign data of localValue to it and storage it on the stack. When the compiler run into the first line in the calculate method. we increase and assign new data for calcValue.

At the last. When compiler print data of localValue to screen, then value of localValue always equal five.

→ So, passing variables into methods in Java is always done by making a copy of the variable.

In another language like c++ we can pass the variables by reference.

#include <stdio.h>//using & keyword to create variable reference.
void swapnum(int &i, int &j) {
int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
printf("A is %d and B is %d\n", a, b); return 0;
}

And out put : A is 20 and B is 10

  • With Object data ?

What happen in java when we passed a Object through argument.

→ For objects passed into methods, the Reference to the object is passed By value. It mean copy a pointer to the object is created, the object itself is not copied.

Example :

running to the first line
2. Call renameCustomer()

The variables c and cust on the Stack both reference to the Customer object on the Heap. And the name of customer had new reference to value is Diane. The data String with value Sally is not reference. It will be remove by GC ( Garbage Collection).

  • Avoid escaping references with custom Object.

If we have a list Customer. we just want to create and can not modify data on original Customer Object.

  • We using the collection ?

When we using method getCustomers(), this return a pointer directly to the Map records and it can do anything likes with that collection. The reference to the map has escaped from the class in which it should have been encapsulated. It’s almost as though we have declare this map as a public variable.

→ So we have violated the encapsulation rules.

And the real pain of this kind of circumstance is that we now have a very difficult job in debugging.
Solution to avoid return a pointer reference to the Map record. We can return a new HashMap<String,Customer>(record), it mean we will create a copy HashMap to do something.

We can see the difference

With case we new ArrayList(collection1) we have create a new Object List on the heap, but we have hold a reference with Customer A and Customer B in collection1.

But we still change data and impact to the original collection. Example : We can rename of CustomerB to CustomerX on collection3, CusomterB on the collection1 will be change to CustomerX at the same time.

change CustomerB to CustomerX

To resolve problem. We want create a immutable HashMap. In java we can do it with Collection. We can using the Collections.unmodifiableMap()

Using Collections.unmodifiableMap

--

--