Blog |

Java Guide: What is Heap Space & Dynamic Memory Allocation?

Java Guide: What is Heap Space & Dynamic Memory Allocation?
Table of Contents

To run Java applications optimally, the JVM divides memory into stack and heap memory. Whenever new variables and objects are declared, new methods are called or other similar operations are performed, the JVM designates memory to these operations from either the Stack Memory or Heap Space.

Heap space is used for the dynamic memory allocation of Java objects and classes at runtime. New objects are always created in the heap space, and references to these objects are stored in the stack memory.

 

Java Heap Space and Generations

The heap space is created by the JVM when it starts. The heap is used as long as the application is running. It can be broken down into smaller parts called generations, which are:

  • Young Generation - All new objects are allocated and aged here. A minor garbage collection occurs when this fills up.
  • Old or Tenured Generation - Long surviving objects are stored here. When objects are stored in the Young Generation, a threshold for the object's age is set. When this threshold is reached, the object is moved to the Old Generation. Garbage collection is usually performed in the Old Generation when it's full. This is called Major GC and it usually takes longer.
  • Permanent Generation (replaced by Metaspace since Java 8) - Consists of JVM metadata for runtime classes and application methods.

 

Java Heap Space Features

Some features of the heap space are:

  • It is accessed via complex management techniques that include the Young, Old and Permanent Generations.
  • Access to the heap is slower than to the stack memory.
  • The heap is not automatically deallocated. It needs the Garbage Collector to free up unused objects to keep memory usage efficient.
  • The heap is not threadsafe and needs to be guarded by keeping the code properly synchronized.

 

Java Heap Size

Referenced Java objects remain active in the heap throughout their lifespan and occupy memory. These objects are globally accessible from anywhere in the application. When objects are no longer referenced, they become eligible for garbage collection to free up the occupied heap memory.

The Java heap size is determined by two JVM attributes, which can be set when launching the application:

  • -Xms to set the initial heap size
  • -Xmx to set the maximum heap size

If an object requires more memory than is available in the heap, the application can encounter an OutOfMemoryError. To learn more about how to solve an OutOfMemoryError, check https://rollbar.com/blog/how-to-handle-outofmemoryerror-exceptions-in-java/.

 

Java Heap Space Example

Here's an example of how memory is allocated in the Java Heap Space using a simple program:

class Vehicle {
    private String make;

    public String getMake() {
        return make;
    }

    public void setMake(String make) {
        this.make = make;
    }
}

public class JavaHeapSpaceExample {
    public static void main(String[] args) {
        String make = "Audi";
        Vehicle vehicle = new Vehicle();
        vehicle.setMake(make);
        System.out.println("Make = " + vehicle.getMake());
    }
}

When the above code is executed, all the runtime classes are loaded into the heap space. The JRE creates stack memory to be used by the main() method thread when it is found.

The string created on line 15 is stored in the String Pool in the heap space. The reference variable for the string is stored in the stack memory. The reference variable vehicle of the type Vehicle is also created in stack memory, which points to the actual object in the heap.

The heap memory stores the instance variables for the object vehicle of type Vehicle.

On line 19, the main() method terminates and the stack memory created for it is destroyed. Since the program ends here, the JRE frees up all memory and ends program execution.

 

Conclusion

Based on the above explanations, the following can be concluded about the Java Heap Space and how it works across these various aspects:

  • Application - The entire application uses the Heap Space during runtime.
  • Size - There are no size limits on the Heap. The -Xms and -Xmx JVM attributes can be used to define the startup size and maximum size of the heap memory.
  • Storage - All newly created objects are stored in the Heap.
  • Object Scope - Objects stored in the Heap are globally accessible.
  • Memory Access - The Heap is accessed via complex memory management techniques that include the Young, Old and Permanent Generations.
  • Life - Heap Space exists as long as the application runs.
  • Efficiency - Heap Space is slower to allocate compared to the stack.
  • Allocation/Deallocation - Heap Space is allocated when new objects are created and deallocated by the Garbage Collector when they are no longer referenced.

 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

Related Resources

"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Error Monitoring

Start continuously improving your code today.

Get Started Shape