Search code examples
javamemoryjvmcluster-analysismoa

Limit memory usage of a java class


I am writing a java class which is to be run with a java MOA framework. The class has functions to cluster a stream of points. This class is called by MOA application. I want to limit the total memory (at least the memory used on heap, can exclude stack memory) usage of this class (excluding the memory used by MOA application).

Is it possible? I hope its clear that the class is being instantiated and called by MOA application. I am running the MOA application first and then chosing to run myclass from GUI to perform the clustering. Because of this reason, the JVM options like -Xmx are not working for me.


Solution

  • You can embed logic in the class to check Runtime.freeMemory() and Runtime.maxMemory() at intervals and take steps (flush caches, etc) when the limit seems to be close. A little "iffy" since different platforms report heap stats differently.

    You can also use a SoftReference scheme for some of your "optional" storage. Then GC will delete objects if it needs the heap. (Though this scheme is using a sledgehammer to swat a mosquito.)

    And you can, of course, simply count your object allocations.