问题
I'm creating a 4096 x 4096 array of my class. When I'm profiling, it's showing that the most memory is used by char arrays. I don't have any char arrays or strings in my class.
Here is my Java class:
public class MyClass {
private int id;
private boolean flag;
public MyClass() {
id = 0;
flag = false;
}
}
And my Main class:
public class Main {
public static void main(String[] args) {
MyClass[][] objects = new MyClass[4096][4096];
for (int i = 0;i<4096;i++) {
for(int j = 0;j<4096;j++) {
objects[i][j] = new MyClass();
}
}
while(true);
}
}
I'm using JVM Monitor for profiling. Why is it showing this?
Here's a screenshot of it running in Eclipse:
回答1:
From your image, it looks like the instances of MyClass
you created aren't even live when you're doing the profiling. The char[]
usage is expected since char arrays back String
s, which are used extensively in class definitions, etc.
It could be that your array is getting garbage collected since it's not used. Try adding a line after the sleep that uses the array, and then try to profile again. Example:
MyClass[][] objects = new MyClass[4096][4096];
for(int i = 0;i<4096;i++)
{
for(int j = 0;j<4096;j++)
{
objects[i][j] = new MyClass();
}
}
Thread.sleep(1000000);
System.out.println(objects[10][40]);
This ensures that the array is not eligible for garbage collection until you've had a chance to profile it.
回答2:
make sure you run System.gc() or similar before taking your heap dump. Else you will see a lot of objects that are no longer referenced in your sample.
来源:https://stackoverflow.com/questions/21908614/jvm-monitor-char-array-memory-usage