How to find total Memory, free Memory and max Memory from Java Runtime?




In this post, we will see how to find total Memory, free Memory and max Memory from Java Runtime. Here, we will use Runtime class to get this information.

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method. An application cannot create its own instance of this class.



package basics;

import java.util.ArrayList;
import java.util.List;

public class MainApp {

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

		System.out.println("runtime.totalMemory " + runtime.totalMemory());
		System.out.println("runtime.freeMemory " + runtime.freeMemory());
		System.out.println("runtime.maxMemory " + runtime.maxMemory());
		runtime.gc();
		long m1 = runtime.freeMemory();

		List<String> someList = new ArrayList();

		for (int n = 0; n < 1000; n++) {
			someList.add("java");
		}

		System.out.println("Memory occupaid by list is " + (m1 - runtime.freeMemory()));
		System.out.println(someList.size());

	}

}






public class Runtime extends Object

https://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html

long freeMemory()
Returns the amount of free memory in the Java Virtual Machine.

void gc()
Runs the garbage collector.

static Runtime getRuntime()
Returns the runtime object associated with the current Java application.

long maxMemory()
Returns the maximum amount of memory that the Java virtual machine will attempt to use.

long totalMemory()
Returns the total amount of memory in the Java virtual machine.



Post a Comment

Previous Post Next Post