Merge pull request #9626 from alimate/BAEL-4138

BAEL-4138: Measuring the Object Sizes in JVM
This commit is contained in:
Eric Martin 2020-07-09 19:32:11 -05:00 committed by GitHub
commit 3292c9d822
6 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,10 @@
package com.baeldung.objectsize;
public class Course {
private String name;
public Course(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.objectsize;
public class InstrumentedSize {
public static void main(String[] args) {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println(ObjectSizeCalculator.sizeOf(course));
}
}

View File

@ -0,0 +1 @@
Premain-Class: com.baeldung.objectsize.ObjectSizeCalculator

View File

@ -0,0 +1,16 @@
package com.baeldung.objectsize;
import java.lang.instrument.Instrumentation;
public class ObjectSizeCalculator {
private static Instrumentation instrumentation;
public static void premain(String args, Instrumentation inst) {
instrumentation = inst;
}
public static long sizeOf(Object o) {
return instrumentation.getObjectSize(o);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.objectsize;
import org.junit.Test;
import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.info.GraphLayout;
import org.openjdk.jol.vm.VM;
public class ObjectSizeUnitTest {
@Test
public void printingTheVMDetails() {
System.out.println(VM.current().details());
}
@Test
public void printingTheProfClassLayout() {
System.out.println(ClassLayout.parseClass(Professor.class).toPrintable());
}
@Test
public void printingTheCourseClassLayout() {
System.out.println(ClassLayout.parseClass(Course.class).toPrintable());
}
@Test
public void printingACourseInstanceLayout() {
String ds = "Data Structures";
Course course = new Course(ds);
System.out.println("The shallow size is :" + VM.current().sizeOf(course));
System.out.println(ClassLayout.parseInstance(course).toPrintable());
System.out.println(ClassLayout.parseInstance(ds).toPrintable());
System.out.println(ClassLayout.parseInstance(ds.toCharArray()).toPrintable());
System.out.println(GraphLayout.parseInstance(course).totalSize());
System.out.println(GraphLayout.parseInstance(course).toFootprint());
System.out.println(GraphLayout.parseInstance(course).toPrintable());
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.objectsize;
import java.time.LocalDate;
import java.util.List;
public class Professor {
private String name;
private boolean tenured;
private List<Course> courses;
private int level;
private LocalDate birthDay;
private double lastEvaluation;
public Professor(String name, boolean tenured, List<Course> courses,
int level, LocalDate birthDay, double lastEvaluation) {
this.name = name;
this.tenured = tenured;
this.courses = courses;
this.level = level;
this.birthDay = birthDay;
this.lastEvaluation = lastEvaluation;
}
}