Java – how do I check the number of objects created in heap memory?

I want to see how many objects Java creates when running the program

My intention is if I use the code string s = new string ("Hi"); I want to see how many objects Java will create Later, I want to try using string news = "Hi";

This is my sample program:

import java.util.Scanner;

public class Test { 
    public static void main(String[] args) {
        String str = new String("Hi");
        Scanner s = new Scanner(system.in);
        s.nextLine();
    }
}

I am using scanner to avoid program termination

I have experienced this so how to find the number of objects in the heap and tried to use jvisualvm, but the tool did not give the count of objects created in my class I also don't understand how to get the actual number of objects according to the figure below

When I try to use the command jmap - heap < PID >, I get the following error:

If I use eclipse debug as an option, I find it is not the right way to find out the number of objects being created

Solution

If you look at the debugger, you can see it

The string @ 437 object is the same in S1, S2 and S3, but this refers to char [2] @ 438, which is another object Therefore, you have two objects

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>