0

I'm learning java, When looking for data, I often see pictures that describe the memory distribution during the running of the program.Just like:

Description polymorphism enter image description here

Description inheritance enter image description here

Combined with the article, I can understand the picture. But I want to know, is there any method or command that allows me to see the memory distribution state in jvm when the java program is running?

I tried to debug my program using jdb, but it didn't give me the memory allocation status in jvm.

The following is my test code, I just need a simple example, use some commands or methods to see the memory allocation of jvm when this code runs.

Project directory structure

.
├── src
│   └── com
│       ├── Index.java
│       └── libs
│           ├── Cat.java
│           ├── Dog.java
│           └── ext
│               └── Animal.java

Animal.java

package com.libs.ext;

public class Animal {

    public void eat() {
        System.out.println("Animal is eating");
    }
}

Dog.java

package com.libs;

import com.libs.ext.Animal;

public class Dog extends Animal {
    public void eat() {
        System.out.println("Dog is eating");
    }
}

Cat.java

package com.libs;

import com.libs.ext.Animal;

public class Cat extends Animal {
    public void jump() {
        System.out.println("Cat is jumping");
    }
    public void eat() {
        System.out.println("Cat is eating");
    }
}

Index.java

package com;

import com.libs.Cat;
import com.libs.Dog;
import com.libs.ext.Animal;

public class Index {

    public static void doEat(Animal animal) {
        animal.eat();
    }

    public static void main(String[] args) {
        Dog d = new Dog();
        Cat c = new Cat();

        Index.doEat(d); //Dog is eating
        Index.doEat(c); //Cat is eating

        c.jump(); //Cat is jumping
    }
}
  • 2
    What you're looking for is called a "heap analyzer". Just google "Java heap analyzer" and go from there. – Kevin Anderson Nov 19 '18 at 04:00
  • It's not quite as fancy in terms of pictures, but you could try this: https://docs.oracle.com/javase/8/docs/technotes/guides/visualvm/index.html – Ryan Nov 19 '18 at 04:00
  • A memory profiler will do that. – Peter Lawrey Nov 19 '18 at 07:16
  • In a real life program, with millions (or billions) of objects, it’s impossible to represent all of them in such a neat graph. As said by others, you can use a heap dump analyzer to solve specific technical questions (e.g. which chain of references is preventing the garbage collection of this object), but even with your simple example program, you might see ten thousands of objects providing the necessary infrastructure for the Java program execution, you didn’t see in your picture. Besides that, inheritance/polymorphism and the memory state are entirely different things. – Holger Nov 19 '18 at 10:27

0 Answers0