Is there a way to predict how much memory my Java program is going to take? I come from a C++ background where I implemented methods such as “size_in_bytes()” on classes and I could fairly accurately predict the runtime memory footprint of my app. Now I’m in a Java world, and that is not so easy… There are references, pools, immutable objects that are shared… but I’d still like to be able to predict my memory footprint before I look at the process size in top.
Share
You can inspect the size of objects if you use the instrumentation API. It is a bit tricky to use — it requires a “premain” method and extra VM parameters — but there are plenty of examples on the web. “java instrumentation size” should find you these.
Note that the default methods will only give you a shallow size. And unless you avoid any object construction outside of the constructor (which is next to impossible), there will be dead objects around waiting to be garbage collected.
But in general, you could use these to estimate the memory requirements of your application, if you have a good control on the amount of objects generated.