Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory is allocated for one Integer object in Java? How to find out this value for any custom object? [duplicate]

What is the proper way to measure how much memory from the heap should be used to create new object of a certain type (let's talk about Integers to keep it simple)?

Can this value be calculated without experiment? What are the rules in that case? Are these rules strictly specified somewhere or they can vary from jvm to jvm?

like image 915
Roman Avatar asked Oct 27 '10 08:10

Roman


2 Answers

It could vary from JVM to JVM.

You may like this blog post from an Oracle engineer:

In the case of a Java Integer on a 32-bit Hotspot JVM, the 32-bit payload (a Integer.value field) is accompanied by a 96 additional bits, a mark, a klass, and a word of alignment padding, for a total of 128 bits. Moreover, if there are (say) six references to this integer in the world (threads plus heap), those references also occupy 192 bits, for a total of 320 bits. On a 64-bit machine, everything is twice as big, at least at present: 256 bits in the object (which now includes 96 bits of padding), and 384 bits elsewhere. By contrast, six copies of an unboxed primitive integer occupy 192 bits

like image 109
Thilo Avatar answered Sep 22 '22 18:09

Thilo


You might wanna look at Java instrumentation to find that out. Here is an example of the same.

In your case, as I believe you want to find size of objects from withing your application, you will make the Instrumentation object available globally (static ) so that you can access it from your application.

Code Copied from the link:

public class MyAgent {
  private static volatile Instrumentation globalInstr;
  public static void premain(String args, Instrumentation inst) {
    globalInstr = inst;
  }
  public static long getObjectSize(Object obj) {
    if (globalInstr == null)
      throw new IllegalStateException("Agent not initted");
    return globalInstr.getObjectSize(obj);
  }
}

However, I believe you will be able to find the size of only objects (not primitive types, also you do not require to find them out as you already know them :-) )

Note that the getObjectSize() method does not include the memory used by other objects referenced by the object passed in. For example, if Object A has a reference to Object B, then Object A's reported memory usage will include only the bytes needed for the reference to Object B (usually 4 bytes), not the actual object.

To get a "deep" count of the memory usage of an object (i.e. which includes "subobjects" or objects referred to by the "main" object), then you can use the Classmexer agent available for beta download from this site.

like image 36
Ankit Avatar answered Sep 24 '22 18:09

Ankit