I have a requirement in my project which I want to discuss here.
In my project we have a configuration file which actually define the cache size.
This cache size is not in terms of no of nodes but in terms of MB, which I feel is completely logical as we always know the memory size of system.
So my question here is, Do we have some way by which we can limit the size of an java object in terms of MB ?
I searched on net and got some class which do some operation to know this which is very costly in terms of CPU cycle.
What I am looking for is some light weight way to do this.
I agree with Rob,
i am doing R&D on it from long time and yet not got anything.
Few library claim to do so but actually they just calculating the difference of java heap size,
which is very indirect and very costly in terms of performance.
java.lang.instrument is also not usefull in anyway.
@Martin : yes, by this way, we can control the heap size of application but not the object
i need to control the size of object.
It is true that you cannot control the memory size allocation for an object but you can use Runtime class to use available memory and maz memory and can implement logic based on that, but but but it is not a perfect way of handling memory.
shanky sohar wrote:why not you often call System.gc().this will garbage collect the unusable object which can save the memory.
No, it will not. You cannot force the garbage collector to run. If you call System.gc(), you are only suggesting to the JVM that it might be good to run the garbage collector. But there's no guarantee that it will actually run.
Also, calling System.gc() does not prevent OutOfMemoryErrors. You only get an OutOfMemoryError if there is really no memory left to allocate; if the garbage collector failed to make enough memory available.
In general, it's better to just let the garbage collector do its job automatically. Calling System.gc() can even have negative effects, like dramatically lowering the performance of your program.
Gaurav Raje wrote:It is known to crash your system at times....... Especially if your application has native code. Even more if it has TSR (Terminate but Stay Resident) native code in it. Bot not just if it does.....
Well... no. Only if your native code has bugs in it.
On to the OP's original question about limiting the size of an object. Note that every class creates objects of some precisely fixed size, depending only on its member variables -- except for arrays. Perhaps what you're really interested in is limiting the size of arrays that can be created? One can imagine using AOP (aspect-oriented programming) do this in at least a limited way.