What is the best way to determine the size of an object in Java?

Asked 2 years ago, Updated 2 years ago, 137 views

For example, you have an application that allows you to read CSV files that are stored, separated by rows of data. You want to summarize the number of rows based on the data type and provide it to the user. However, a OutOfMemoryError occurred, preventing many rows of data from being read. Convert each row to one object. Is there an easy way to figure out the size of an object by programming? Is there a criterion for determining the size of the primitive type and reference type in VM?

I made a source code that reads about 32000 lines. However, I want to make the row data readable until I use about 32MB of memory. This is a little different from the previous question. I want to know this, too.

memory java

2022-09-22 21:31

1 Answers

Use java.lang.instrument package.

Compile the following classes and put them in JAR:

import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}

And add the following to MANIFEST.MF.

Premain-Class: ObjectSizeFetcher

Use getObjectSize:

public class C {
    private int x;
    private int y;

    public static void main(String [] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}

And do it as follows:

java -javaagent:ObjectSizeFetcherAgent.jar C


2022-09-22 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.