Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Stack vs. Heap: Understanding Java Memory Allocation

DZone's Guide to

Stack vs. Heap: Understanding Java Memory Allocation

Know the difference between stack and heap? When it's right to use which one, and what features they offer? Here's a guide to memory allocation.

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Stack and heap are two important concepts you should understand in relation to Java memory allocation. Let’s take a look at the two concepts, why they matter, and when you should use each.

What Is Java Stack?

A Java stack is part of your computer’s memory where temporary variables, which are created by all functions you do, are stored. It is used to execute a thread and may have certain short-lived values as well as references to other objects. It uses LIFO data structure, or last in first out.

What does this mean? When a method is invoked, it creates a new block in the stack for that particular method. The new block will have all the local values, as well as references to other objects that are being used by the method. When the method ends, the new block will be erased and will be available for use by the next method. The objects you find here are only accessible to that particular function and will not live beyond it.

This makes it very easy to keep track of the stack, where the latest reserved block is also the first to be freed. The variables created for the method are directly stored in the memory, allowing for fast access.

The memory size of a Java stack is generally much less than in a Java heap space because when a method ends, all the variables created on the stack are erased forever.

Here’s an example of how to create an object in the stack:

void somefunction( )
{
    /* create an object "m" of class Member
    this will be put on the stack since the
    "new" keyword is not used, and we are
    creating the object inside a function
    */

    Member m;

} //the object "m" is destroyed once the function ends


What Is Java Heap?

Java objects are in an area, which is called the heap. It is created when the program is run, and its size may decrease or increase as your program runs. It can easily become full, and when it does, garbage collection is initiated. This is when objects that are no longer used are deleted to make way for new objects.

Unlike in a Java stack where memory allocation is done when your program is compiled, in a heap it is allocated as your program is run. Accessing variables placed here is a bit slower compared to a stack’s direct and fast access.

Heap is likened to a global memory pool. A method or function will use the heap for memory allocation if you need the data or variables to live longer than the method or function in question. The objects you find here are accessible to all the functions.

Also, there is no specific order in reserving blocks in a heap. You can allocate blocks at any time, and then you can free it when you wish. As you can imagine, it is much more complex to keep track of the parts that are free and can be allocated, but it can also be divided into two generations or sub-areas.

These sub-areas are called the young space (or nursery) and the old space. The young space is typically earmarked for the memory allocation for new objects. When the young space becomes full, garbage collection happens. Short-lived or temporary objects typically use the young space. This help makes garbage collection faster when compared to a heap without any divisions.

Here’s an example of how to create an object in the heap:

void somefunction( )
{
    /* create an object "m" of class Member
      this will be put on the heap since the 
      "new" keyword is used, and we are 
      creating the object inside a function
    */
  
    Member* m = new Member( );
  
    /* the object "m" must be deleted
      otherwise a memory leak occurs
    */

    delete m; 
} 


Similarities and Differences Between Stack and Heap

Both are ways that Java allocates memory and both are stored in the RAM. However, to make things easier to remember, heap is used for dynamic memory allocation, while stack is for static allocations.

Where is it stored? Variables that are allocated on the stack are accessible directly from memory, and as such, these can run very fast. Accessing objects on the heap, on the other hand, takes more time.

When does the allocation happen? On the stack, memory allocation happens when the program is compiled. Meanwhile, on the heap, it begins when the program is run.

And since this is the case, you would need to know just how much data and memory you are going to need before compiling if you want to use the stack. Another limitation that the stack has is that it cannot handle big chunks of variables that need a lot of memory. If you do not know how much data you are going to need at run time or if you need memory for a lot of data, then you need to use heap.

In a Nutshell…

Stack

  • The size of the stack will vary as methods and functions create and delete local variables as needed.
  • Memory is allocated and then subsequently freed without you needing to manage the memory allocation.
  • Stack has size limits, which can vary according to the operating system you use.
  • Variables that are stored on the stack exist for as long as the function that created them are running.

Heap

  • Memory is not managed automatically nor is it as tightly managed by the central processing unit the way stack is managed. You would need to free allocated memory yourself when these blocks are no longer needed.
  • The heap is prone to memory leaks, where memory is allocated to unused objects and will not be available to processes other than that.
  • There is no size limit in the heap.
  • Compared to stack, objects in the heap are much slower to access. It is also slower to write to the memory on the heap.

Stack is easier and faster to use, but it comes with a lot of limitations that you can ignore if you use heap.

When do you use stack?  Stack can only be used for local variables that use up small amounts of memory. The good news is that memory allocation and management is not going to be your problem and access to these objects is very fast. It does suffer from size limitations and the fact that you cannot resize variables on the stack.

When do you use heap? You use the heap to allocate memory if there are variables that you need to be accessed globally, as opposed to just being available only to the methods and functions that created it. Heap is also good when you have a need for a lot of memory since it has no limit on memory size. You can also resize the variables on the heap.

Additional Resources and Tutorials

To learn more about the differences between stack and heap, and the best use cases for each, visit the following resources and tutorials:

Stack and heap are two ways Java allocates memory. Heap is better in instances in which you have variables requiring global access, while stack is your go-to for local variables requiring only small amounts of memory. Understanding when and how to use a stack and a heap is critical for developing better Java programs.

It’s also helpful to understand how memory allocation works when dealing with memory leaks. For a comprehensive guide to all the tools, websites, blogs, and other resources you need to level-up your Java game, download our Comprehensive Java Developer’s Guide.

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
memory allocation ,java ,stack ,heap ,tutorial

Published at DZone with permission of Angela Stringfellow, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}