Limit memory usage of a java class

1.6k Views Asked by At

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.

2

There are 2 best solutions below

3
Hot Licks On BEST ANSWER

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.

2
Peter Lawrey On

You can only limit memory usage global for a JVM.

To limit the usage of a class, you need to start another JVM and use that class in the new JVM.

However, it usually best to fix your code so the class never uses too much memory. ;)