Demonstrate totalMemory(), freeMemory() and gc(). : Runtime System « Development « Java Tutorial

class MemoryDemo {
  public static void main(String args[]) {
    Runtime r = Runtime.getRuntime();
    long mem1, mem2;
    Integer someints[] = new Integer[1000];

    System.out.println("Total memory is: " + r.totalMemory());

    mem1 = r.freeMemory();
    System.out.println("Initial free memory: " + mem1);
    mem1 = r.freeMemory();
    System.out.println("Free memory after garbage collection: " + mem1);

    for (int i = 0; i < 1000; i++)
      someints[i] = new Integer(i); // allocate integers

    mem2 = r.freeMemory();
    System.out.println("Free memory after allocation: " + mem2);
    System.out.println("Memory used by allocation: " + (mem1 - mem2));

    for (int i = 0; i < 1000; i++)
      someints[i] = null;

    r.gc(); // request garbage collection

    mem2 = r.freeMemory();
    System.out.println("Free memory after collecting" + " discarded Integers: " + mem2);


6.47.Runtime System
6.47.1.Milliseconds elapsed since January 1, 1970
6.47.2.Demonstrate totalMemory(), freeMemory() and gc().
6.47.3.Demonstrate exec().
6.47.4.Wait until notepad is terminated.
6.47.5.Timing program execution.
6.47.6.Using arraycopy().
6.47.7.Display the total amount of memory in the Java virtual machine.
6.47.8.Display the maximum amount of memory
6.47.9.Display the amount of free memory in the Java Virtual Machine.
6.47.10.Get Number of Available Processors
6.47.12.Execute system command
6.47.13.Determine when the application is about to exit
6.47.14.Execute a command from code
6.47.15.Execute a command with more than one argument
6.47.16.Launch a Unix script with Java
6.47.17.Read output from a Command execution
6.47.18.Send an Input to a Command
6.47.19.From Runtime.exec() to ProcessBuilder
6.47.20.Registering Shutdown Hooks for Virtual Machine