Lesson Learnt : Basic Java Memory Consumption for In-memory Cache.
I know that these days we’re in the era of cheap memory. You can pretty much get 8GB of memory on a Notebook off the shelf. I can still remember in the past when I was playing with my 486DX with 64Mb or memory and it was too fast! yeah. People might question what am I doing using a lot of memory and why would you care. In my case, I’m building a cache which I have to pretty much hold every single object inside the memory. I have over 1 million objects. Well it’s just 1 million objects which it’s not a big deal but I have to index and make it searchable which I was told to use hibernate search. Hiberate search is pretty much a wrapper on top of Lucene. That’s why my my cache it’s very memory consuming. So, I have to be very careful what I put in my domain object. The example I’m using it’s just a basic example which in the real project there will be much more than just this.
For example, I have one Store object which it has a method to return jsonified string. So, what I did I just passed ObjectMapper to transform my object to be json. However, what I didn’t realise was that if I passed that from the constructor my object has to store ObjectMapper inside the object as well and ObjectMapper is a really beefy object. So, If I created a million objects I have to hold another million objects of ObjectMapper as well. So, I just had to pass ObjectMapper just when I want to use it. And that save me a lot of memory.
Result from passing ObjectMapper from the constructor.
Result from passing ObjectMapper just when I want to use it.
I know this might be obvious for some people but if you have the same problems as myself this might help shed some lights to something else.