devxlogo

Determining Memory Usage

Determining Memory Usage

Question:
Is there a way to determine the percentage of CPU usage or RAM usagewithin a Java application?

Answer:
Java does not provide an API for determining CPU usage, but it does make memory usage information available. The java.lang.Runtime class has two methods that provide information about memory resources.

The totalMemory() method will return the total amount of memory available to the JVM. This value includes both memory in use and memory yet to be allocated. The freeMemory() method will return the amount of unallocated memory in the JVM. This is memory that can be used to create new objects. Neither of these values can be relied upon to stay fixed. The total memory available to a JVM can increase or decrease as the JVM dynamically adjusts itsresource consumption. Remember, the JVM is a process running on theoperating system that allocates some system memory for its use. As aJava program starts using up this memory, the JVM can allocate morememory from the operating system. By the same token, when a Javaprogram’s memory usage decreases, the JVM can reduce the amount of system memory used.

The following example program demonstrates how to get memory usage information,and also how the reported values can change throughout the executionof a program. The example starts out by printing out the totalmemory, free, and used memory. Then it allocates 1 Megabyte of memoryin an array and prints out the memory usage again. Finally, it setsthe array to null, making its memory eligible for garbage collection,requests that the garbage collector be executed, and prints out thefinal memory usage values. You should see the total and used memoryvalues increase after the initial memory allocation and only the freememory increase after the garbage collection.

public class MemoryUsage {  public static void printUsage(Runtime runtime) {    long total, free, used;    total = runtime.totalMemory();    free  = runtime.freeMemory();    used = total - free;    System.out.println("
Total Memory: " + total);    System.out.println("        Used: " + used);    System.out.println("        Free: " + free);    System.out.println("Percent Used: " + ((double)used/(double)total)*100);    System.out.println("Percent Free: " + ((double)free/(double)total)*100);  }  public static final void main(String[] args) {    Runtime runtime;    byte[] bytes;    // Print initial memory usage.    runtime = Runtime.getRuntime();    printUsage(runtime);    // Allocate a 1 Megabyte and print memory usage    bytes = new byte[1024*1024];    printUsage(runtime);    bytes = null;    // Invoke garbage collector to reclaim the allocated memory.    runtime.gc();    // Wait 5 seconds to give garbage collector a chance to run    try {      Thread.sleep(5000);    } catch(InterruptedException e) {      e.printStackTrace();      return;    }    // Total memory will probably be the same as the second printUsage call,    // but the free memory should be about 1 Megabyte larger if garbage    // collection kicked in.    printUsage(runtime);  }}

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist