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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.