Exploring memory layout in Java Baeldung

I am experimenting with inheritance and for educational purposes, I want to consider the addresses allocated for different objects and fields within an object. Is there a tool that will allow me to see what memory the JVM is using and what it is using it for.

For example, if I have two classes:

class A { int i,j; int f { ...} }
class B extends A { int c; /* more methods, overriding f and declaring new ones as well */ }

      

and create these classes in objects a

and b

.

Is there a tool I can use to profile memory usage and determine exactly what memory is allocated for them?

Thank!

+3


source to share


3 answers


I think it is instructive at first to have an idea of ​​how the JVM works on some operating system, so take a look at the Java Virtual Machine.Also related question: https://softwareengineering.stackexchange.com/questions/151076/approaching-java -jvm-internals



+2


source


Since the original question was posted, the situation has changed slightly.

The jol tool ("linking Java objects", Alexei Shipilev), now part of OpenJDK, allows you to check the actual memory structure and class usage. http://openjdk.java.net/projects/code-tools/jol/



Sample output looks like this:

$ java -jar jol-cli/target/jol-internals.jar java.util.HashMap
  Running 64-bit HotSpot VM.
  Using compressed references with 3-bit shift.
  Objects are 8 bytes aligned.
  Field sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]
  Array element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]

  java.util.HashMap object internals:
   OFFSET  SIZE       TYPE DESCRIPTION                    VALUE
        0     4            (object header)                01 00 00 00 (00000001 00000000 00000000 00000000)
        4     4            (object header)                00 00 00 00 (00000000 00000000 00000000 00000000)
        8     4            (object header)                0f 0f 3e e0 (00001111 00001111 00111110 11100000)
       12     4        Set AbstractMap.keySet             null
       16     4 Collection AbstractMap.values             null
       20     4        int HashMap.size                   0
       24     4        int HashMap.threshold              16
       28     4      float HashMap.loadFactor             0.75
       32     4        int HashMap.modCount               0
       36     4        int HashMap.hashSeed               0
       40     4    Entry[] HashMap.table                  []
       44     4        Set HashMap.entrySet               null
  Instance size: 48 bytes (estimated, add this JAR via -javaagent: to get accurate result)
  Space losses: 0 bytes internal + 0 bytes external = 0 bytes total

      

+8


source


No, no such tool exists, but this article explains the basics of how memory layout works, for example. OpenJDK. (Notably, additional methods in a class take zero overhead in instances of that class.)

0


source







All Articles