Suresh Atta
Suresh Atta

Reputation: 121998

How much memory allocates to element in Object[]

Consider the below case

int[] anArray = new int[10]; 

Allocates memory for 10 elements of each 32-bit on heap.Right ?

So what is the size of the element if the element type is Object. ??

like

Object[] objArray = new Object[10];

How much memory allocated now on heap ? I just got the doubt by ssing the source code of ArrayList.

  private transient Object[] elementData;

Just tried this line in my machine

List<String> s = new ArrayList<String>(Integer.MAX_VALUE);

results

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at java.util.ArrayList.<init>(Unknown Source)
    at com.nextenders.server.guice.actions.servlets.Test.main(Test.java:13)

So I'm trying to know how much memory allocated.

Upvotes: 4

Views: 192

Answers (3)

Stephen C
Stephen C

Reputation: 718678

So what is the size of the element if the element type is Object. ??

The size of an Object[] array element is the size of a reference.

  • On a 32 bit JVM, a reference is 32 bits (4 bytes)

  • On a 64 bit JVM, a reference is 64 bits (8 bytes), or 32 bits if the "compressed oop" optimization is enabled and the heap size is less than 32Gb.

So your array allocation will allocate a heap object containing roughly 4 x 10 or 8 x 10 bytes ... plus about 12 bytes of object header overhead.

Just tried this line in my machine

List<String> s = new ArrayList<String>(Integer.MAX_VALUE);

Under the covers, you are attempting to allocate attempting to allocate an array containing between 233 and 234 bytes. With a 32bit JVM, that is guaranteed to not work. With a 64 bit JVM, you'd need a heap of at least 8Gb (compressed oop) or 16Gb for that to work.

Upvotes: 4

06needhamt
06needhamt

Reputation: 1605

It will create an array of 10 32 bit references to objects (the memory address where the object is stored) as all objects in java are just pointers to the memory where the object is stored. Or if you are using a 64 bit machine the addresses will be 64 bits

Upvotes: 0

Minh
Minh

Reputation: 361

  1. 10 x 4bytes = 40 bytes
  2. The maximum size for the object store is 256 MB of compressible, nonvolatile, RAM storage. The size of the object store can be changed to customize the amount of persistent storage available for applications and their related data. default Object = 4bytes in x32bit and 8bytes in x64bit
  3. It is depend on what items of object are holding. Since you are not assign any items in object so the Heap will be calculate by default Object = 4bytes x 10 = 40bytes.

Upvotes: 0

Related Questions