Java Runtime freeMemory()

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

1. Runtime freeMemory() Method Overview

Definition:

The Runtime.freeMemory() method returns the amount of free memory in the Java Virtual Machine (JVM). This represents the amount of memory that is currently unallocated and can be used by new objects created in the application.

Syntax:

public long freeMemory()

Parameters:

- None.

Key Points:

- The returned value represents the current amount of free memory, in bytes.

- This method can be useful in performance monitoring to gauge how much memory an application is consuming over time.

- Remember that the value is not constant and can change as objects are allocated and garbage collected.

- Calling System.gc() can potentially reclaim unused memory, but it's generally not recommended to force garbage collection in a typical application since it can cause performance hitches.

2. Runtime freeMemory() Method Example

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

        long initialFreeMemory = runtime.freeMemory();
        System.out.println("Initial free memory: " + initialFreeMemory + " bytes");

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

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

        long consumedMemory = initialFreeMemory - afterAllocation;
        System.out.println("Memory consumed by allocation: " + consumedMemory + " bytes");
    }
}

Output:

Initial free memory: 12345678 bytes
Free memory after allocation: 11789456 bytes
Memory consumed by allocation: 56222 bytes

(Note: The output values are hypothetical and will differ based on your JVM's configuration and current state.)

Explanation:

In the provided example, we first determine the initial free memory using the freeMemory() method. 

We then allocate an array of integers, consuming a portion of the JVM's available memory. By checking the free memory again after the allocation, we can deduce how much memory was consumed by our array allocation. 

This demonstrates how you can monitor memory usage and see the impact of various operations on the available memory in the JVM.

Comments