1. Overview

In this article, we’ll discuss the APIs provided by Java that can help us understand the several aspects related to Java heap space.

This can be useful in understanding the current memory status of the JVM and outsourcing it to monitoring services such as StatsD and Datadog which can then be configured to take pre-emptive action and avoid application failures.

2. Accessing Memory Parameters

Every Java application has a single instance of _java.lang.Runtime _that can help us understand the current memory status of the application. The _Runtime#getRuntime _static method can be called to get the singleton Runtime instance.

2.1. Total Memory

The Runtime#getTotalMemory method returns the total heap space currently reserved by the JVM in bytes. It includes the memory reserved for current and future objects. Hence, it isn’t guaranteed to be constant during the program execution since the Java heap space can be expanded or reduced as more objects are allocated.

Also, this value isn’t necessarily what is in use or the maximum memory available.

2.2. Free Memory

The Runtime#freeMemory method returns the free heap space available for new object allocations in bytes. It may increase as a result of a garbage collection operation where more free memory is available after.

2.3. Maximum Memory

The _Runtime#maxMemory _method returns the maximum memory that the JVM will attempt to use. Once the JVM memory usage reaches this value, then it will not allocate more memory and instead, and it will garbage collect more frequently.

If the JVM objects still need more memory even after the garbage collector is run then the JVM may throw a _java.lang.OutOfMemoryErro_r runtime exception.

3. Example

#maven #java #architecture-design

A practical of applying Java Modules in a Hexagonal Architecture
3.15 GEEK