Java Runtime totalMemory()

In this guide, you will learn about the Runtime totalMemory() method in Java programming and how to use it with an example.

1. Runtime totalMemory() Method Overview

Definition:

The Runtime.totalMemory() method returns the total amount of memory currently available for current and future objects, measured in bytes, within the JVM.

Syntax:

public long totalMemory()

Parameters:

- None.

Key Points:

- The returned value represents the current total memory allocated to the JVM, not the maximum possible memory.

- The total memory consists of used and unused memory.

- While Runtime.freeMemory() gives you the amount of memory not currently allocated, Runtime.totalMemory() minus Runtime.freeMemory() gives you the actual memory currently in use by your application.

- The JVM might increase the allocated memory pool over time, up to the maximum memory limit, based on application demands.

2. Runtime totalMemory() Method Example

public class TotalMemoryCheck {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        long initialTotalMemory = runtime.totalMemory();
        System.out.println("Initial total memory: " + initialTotalMemory + " bytes");

        // Allocate large number of integers
        int[] array = new int[1_000_000];

        long afterAllocation = runtime.totalMemory();
        System.out.println("Total memory after allocation: " + afterAllocation + " bytes");

        long differenceInMemory = afterAllocation - initialTotalMemory;
        System.out.println("Difference in memory after allocation: " + differenceInMemory + " bytes");
    }
}

Output:

Initial total memory: 25794976 bytes
Total memory after allocation: 25794976 bytes
Difference in memory after allocation: 0 bytes

(Note: The output values are hypothetical and may differ based on your JVM's configuration and current state. In some cases, you may see a difference in total memory after the allocation, especially if the JVM decides to increase its memory pool.)

Explanation:

In the provided example, we first determine the initial total memory using the totalMemory() method. 

After that, we allocate an array of integers. We then measure the total memory again. The difference in memory before and after allocation provides an indication of how the JVM's memory pool is being utilized or if it has been expanded. 

This method helps in understanding how memory is managed by the JVM and can be used in conjunction with other Runtime methods for a more comprehensive view of the application's memory utilization.

Comments