0

when we define a Java class, we can get the Obeject's memory usage in heap,but we cannot get the runtime memory usage becasuse of the program's unknown behaviors。such as the follow class:

public class Sample{
   private int age;
   private String name;
   private static List scores = new ArrayList<Integer>();
   public static void main(String[] args){
     Scanner sc = new Scanner(System.in);
     while(sc.hasNext()){
       scores.add(sc.nextInt());
     }
   }
}

then how do we get the runtime memory usage of the class Sample?

killer_nudt
  • 91
  • 2
  • 2
  • 6
  • There are a number of techniques outlined here: https://stackoverflow.com/questions/21535189/jvm-deep-memory-size-of-an-object – Nicholas Sep 13 '18 at 13:44

2 Answers2

1

there are multiple tools to do so. you can use jvisualvm which is in your JDK. Alternatively, there are some commercial ones too. for further information, you can follow this link. Moreover, you can install "visual GC" plugin on jvisualvm which shows you change on different parts of your heap e.g.: Eden, survivors, old gen, metaspace. Even time to perform GC and time to load classes are trackable.

To install a plugin on jvisualvm from Tools->plugins.

1

You can get another java parameters such as "Used Memory" like this:

public class Sample{
   private int age;
   private String name;
   private static List scores = new ArrayList<Integer>();
   public static void main(String[] args){
     Scanner sc = new Scanner(System.in);
     while(sc.hasNext()){
       scores.add(sc.nextInt());
     }

        Runtime runtime = Runtime.getRuntime();

        System.out.println("Used Memory:" 
            + (runtime.totalMemory() - runtime.freeMemory()));

        System.out.println("Free Memory:" 
            + runtime.freeMemory());

        System.out.println("Total Memory:" + runtime.totalMemory());

        System.out.println("Max Memory:" + runtime.maxMemory());
   }
}

if you like to calculate a class usage you have to get this params before and after run than class and compare the numbers

Danial Jalalnouri
  • 609
  • 1
  • 7
  • 18