Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an object in java have any memory size constraints?

Can we have any size of Java object without any fear of exception? I am going to use an object of a class that consists of an ArrayList of thousands of other objects that contains couples of HashMaps and ArrayLists and many other non primitive type.

Thank you

like image 265
R. Rahul Avatar asked Sep 01 '10 12:09

R. Rahul


People also ask

Does object occupy memory in Java?

In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In JAVA , when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.

What is the size of an object in Java?

Objects, References and Wrapper Classes. Minimum object size is 16 bytes for modern 64-bit JDK since the object has 12-byte header, padded to a multiple of 8 bytes. In 32-bit JDK, the overhead is 8 bytes, padded to a multiple of 4 bytes.

Which memory are objects stored in Java?

The heap is used for storing objects in memory.

How long will an object take up memory in Java?

Each data member takes up 4 bytes, except for long and double which take up 8 bytes. Even if the data member is a byte, it will still take up 4 bytes! In addition, the amount of memory used is increased in 8 byte blocks.


1 Answers

If you have an object (let's call it A) that references an ArrayList with many, many objects in it, the "size" of A will still be rather small (the size of the reference plus a bit of overhead). Objects referenced by A are pretty much independent from A. The only limit is that the total size of all objects is limited by the available memory.

The only truly "huge object" would be one with many, many fields, but there the JLS/JVM spec sets a pretty small limit (the fields_count in the class file format is an u2 field, so you can have at most 65 535 fields).

like image 97
Joachim Sauer Avatar answered Sep 23 '22 12:09

Joachim Sauer