Skip to main content

Posts

Showing posts with the label Tips

Java - Getting the memory size of an object.

Because the way Java language and the way JVMs are implemented, this apparently trivial task is more complex than it may seem specially when compared to C++ where all objects have a size() method. Java memory architecture is built to abstract the developer from direct manipulation of memory so that the developer can focus on more relevant tasks, this comes with a price. There are 3 basic approaches you can take in order to do this all with their pros and cons: Memory guess (Heap Size prior object creation - Heap Size after object creation = Object Size) Java Instrumenting Query Serialization Memory Guess This is the simplest approach because of the fact that you have a pretty easy access to the Heap Size via: Runtime.getRuntime().totalMemory(); The issue with this approach is that you cannot control what is being thrown into the heap at a given time, JVM is shared by a lot of processes that run in a given machine so this is a error prone approach that is not recommend