Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, what is the best way to determine the size of an object?

Tags:

java

memory

I have an application that reads 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.

like image 997
Jay R. Avatar asked Sep 09 '08 17:09

Jay R.


People also ask

What is the use of size () in Java?

The size() in Java is a predefined method of the ArrayList class. It is used to calculate the number of objects in an ArrayList. It Does not take any input parameter, and whenever the ArrayList calls this function, it returns an integer representing the number of elements of ArrayList.

Which operator can be used to check the size of an object?

Which operator can be used to check the size of an object? Explanation: The sizeof operator is used to get the size of an already created object. This operator must constail keyword sizeof(objectName). The output will give the number of bytes acquired by a single object of some class.

What is size of a class in Java?

Java Class Any class in Java is nothing but an object with a mix of all mentioned components: header (8 or 12 bytes for 32/64 bit os). primitive (type bytes depending on the primitive type). object/class/array (4 bytes reference size).


1 Answers

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 the getObjectSize() method:

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 
like image 52
Stefan Karlsson Avatar answered Oct 07 '22 06:10

Stefan Karlsson