IN JAVA, WHAT IS THE BEST WAY TO DETERMINE THE SIZE OF AN OBJECT?

jayprakash sharma

Total Post:117

Points:821
Posted by  jayprakash sharma
Java 
 945  View(s)
Ratings:
Rate this:
For example, let's say I have an application that can read in a CSV file with piles of data rows. I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors. Each row translates into an object. Is there an easy way to find out the size of that object programmatically? Is there a reference that defines how large primitive types and object references are for a VM?

Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory. Maybe that is a different question, but I'd still like to know.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: In Java, what is the best way to determine the size of an object?

    You can use the java.lang.instrument package

    Compile and put this class in a 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);
        }
    }
    Add the following to your 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()));
        }
    }
    Invoke with:

    java -javaagent:ObjectSizeFetcherAgent.jar C

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!