Back to Java
2026-01-057 min read

Bash Memory Usage (free) (Java)

Learn Bash Memory Usage (free) (Java) step by step with clear examples and exercises.

Title: Bash Memory Usage (Free) (Java) - Expanded Lesson

Why This Matters

In Java, understanding how to check memory usage is crucial for efficient programming. It helps you optimize your code, avoid runtime errors, and diagnose issues related to memory leaks. In this lesson, we'll explore Bash commands that allow you to monitor free and used memory in a Java application.

Importance of Monitoring Memory Usage

Monitoring memory usage is essential for several reasons:

  1. Optimization: By keeping track of memory consumption, developers can identify areas where their code can be optimized to reduce memory usage and improve performance.
  2. Error Prevention: Regularly monitoring memory usage helps prevent runtime errors such as OutOfMemoryErrors that can cause your application to crash.
  3. Debugging Memory Leaks: Monitoring memory usage can help diagnose and fix memory leaks, which can significantly impact the stability and efficiency of a Java application.
  4. Understanding System Behavior: Analyzing memory usage patterns can provide insights into how your application behaves under different loads and help you make informed decisions about scaling or optimizing resources.

Prerequisites

To follow along with this tutorial, you should have:

  1. Basic knowledge of the Java programming language
  2. Familiarity with the Linux/Unix command line (Bash)
  3. A text editor like nano or vim to write and edit scripts
  4. A running Java application for testing purposes
  5. Knowledge of JVM options related to memory management (e.g., -Xms, -Xmx)
  6. Familiarity with the concept of heap memory in Java applications
  7. Practice Question 1: Write a simple Java program that allocates a large array and monitors its effect on memory usage using the free command.
  8. Practice Question 2: Modify the Java program from Practice Question 1 to include JVM options for monitoring memory usage (e.g., -verbose:gc, -XshowSettings:vm).

Core Concept

To display free and used memory in a Java application, we'll use Bash commands that interact with the operating system's kernel. The free command is the most common tool for this purpose.

The free Command

The free command provides an overview of the system’s memory usage, including total, used, and free memory in kilobytes (KB) and megabytes (MB). By default, it displays information about both physical and swap memory.

free -h

The -h flag makes the output more human-readable by showing the values in MB instead of KB.

Java Heap Memory

Java applications use a managed heap for storing objects created during runtime. The JVM (Java Virtual Machine) controls the allocation and deallocation of memory within this heap. To monitor the Java heap, we can use tools like jmap or visualvm. However, in this tutorial, we'll focus on Bash commands to get an idea of how much memory our Java application is consuming.

Heap Memory Regions

The JVM divides the heap into several regions:

  1. New Generation: Consists of Eden space, Survivor spaces (from -XX:SurvivorRatio), and Tenured generation (Old or PermGen).
  2. Tenured Generation (Old/PermGen): Holds long-lived objects that have survived multiple garbage collections.
  3. Metaspace: Replaces the PermGen space in Java 8 and later versions, used for class metadata and static variables.

JVM Options for Monitoring Memory Usage

The JVM provides several options to help monitor memory usage during runtime. Some commonly used flags are:

  1. -Xms: Sets the initial heap size (minimum) in bytes.
  2. -Xmx: Sets the maximum heap size (maximum) in bytes.
  3. -Xss: Sets the stack size for each thread in bytes.
  4. -XX:+HeapDumpOnOutOfMemoryError: Generates a heap dump file when an OutOfMemoryError occurs.
  5. -verbose:gc: Enables verbose garbage collection output, providing information about when and why garbage collections occur.
  6. -XshowSettings:vm: Prints the JVM settings used for the current invocation.

Worked Example

Let's create a simple Java program that consumes memory and monitor its usage using the free command.

  1. Create a new file named MemoryTest.java with the following content:
public class MemoryTest {
public static void main(String[] args) throws InterruptedException {
long size = 1024 * 1024 * 50; // 50 MB
byte[] array = new byte[size];

System.out.println("Memory allocated: " + size + " bytes");

// Simulate some processing to observe memory usage changes
Thread.sleep(60_000); // Sleep for 1 minute
}
}
  1. Compile the program using javac MemoryTest.java.
  2. Run the compiled program with java MemoryTest. You should see output similar to:
Memory allocated: 5368709120 bytes
  1. Now, let's check the memory usage before and after running the Java application using the free command:

Before running the Java program

free -h

After running the Java program for 1 minute

java MemoryTest & sleep 60 ; free -h


You should see an increase in used memory after running the Java program.

### Interpreting the Results

In the worked example, we ran the Java application and then waited for a minute before checking the memory usage again using the `free` command. This simulates a scenario where the Java application has been running for some time and has had an opportunity to consume more memory.

By comparing the memory usage before and after running the Java application, you can get an idea of how much memory your application is consuming and monitor its growth over time.

### Using JVM Options for Monitoring Memory Usage

To illustrate the use of JVM options for monitoring memory usage, let's recompile our `MemoryTest` program with additional flags:

javac -Xms10m -Xmx50m MemoryTest.java

java -verbose:gc MemoryTest & sleep 60 ; free -h


In this example, we've set the minimum heap size to 10 MB and the maximum heap size to 50 MB using `-Xms` and `-Xmx`, respectively. The `-verbose:gc` flag enables verbose garbage collection output, which will provide information about when and why garbage collections occur during runtime.

Common Mistakes

  1. ### Not Monitoring Memory Usage

Many developers overlook monitoring memory usage and end up with memory leaks or performance issues. Always keep an eye on your application's memory consumption during development and testing.

  1. ### Ignoring JVM Options for Memory Management

Proper configuration of JVM options like -Xms, -Xmx, and -Xss can help optimize the Java heap and improve performance. Developers should understand these options and adjust them according to their application's requirements.

  1. ### Not Properly Cleaning Up Resources

In some cases, objects in a Java program may not be properly cleaned up, leading to memory leaks. It's essential to ensure that all resources are closed or garbage collected when they are no longer needed.

  1. ### Running Memory-Intensive Tasks Without Monitoring

When running memory-intensive tasks, it's important to monitor the memory usage and adjust the heap size if necessary. Failing to do so can lead to OutOfMemoryErrors and application crashes.

  1. ### Not Properly Configuring JVM Options for Production Environments

In production environments, it's essential to configure JVM options appropriately based on the server's memory capacity, expected load, and application requirements. This can help ensure optimal performance and stability.

FAQ

  1. How do I check the current Java heap size?

You can use the java command with the -XshowSettings:vm option to display the JVM settings used for the current invocation, including the heap sizes. For example:

java -XshowSettings:vm MemoryTest
  1. What is the difference between Eden space and Survivor spaces?

Eden space is the primary area where new objects are allocated in the Java heap. When an object survives a garbage collection cycle, it moves to one of the Survivor spaces (from -XX:SurvivorRatio). If an object survives multiple cycles, it eventually moves to the Tenured generation or Old space.

  1. How do I generate a heap dump file when an OutOfMemoryError occurs?

You can use the -XX:+HeapDumpOnOutOfMemoryError option to generate a heap dump file when an OutOfMemoryError occurs. For example:

java -XX:+HeapDumpOnOutOfMemoryError MemoryTest
  1. What is Metaspace, and why was it introduced in Java 8?

Metaspace replaced the PermGen space in Java 8. It is used for class metadata and static variables, and its size can be dynamically adjusted by the JVM based on available memory. Unlike the PermGen space, Metaspace does not have a fixed maximum size.

  1. How do I monitor garbage collection in a Java application?

You can use the -verbose:gc option to enable verbose garbage collection output, which will provide information about when and why garbage collections occur during runtime. For example:

java -verbose:gc MemoryTest
  1. What is swap memory, and how does it affect Java applications?

Swap memory is a virtual memory space used by the operating system to temporarily store data that doesn't fit into physical RAM. When a Java application requires more memory than available in physical RAM, it may use swap memory. However, using swap memory can significantly slow down the application due to the higher latency associated with accessing swap memory compared to physical RAM.

Practice Questions

  1. Write a simple Java program that allocates a large array and monitors its effect on memory usage using the free command.
  2. Modify the Java program from Practice Question 1 to include JVM options for monitoring memory usage (e.g., -verbose:gc, -XshowSettings:vm).
Bash Memory Usage (free) (Java) | Java | XQA Learn