I need to refactor my project in order to make it immune to OutOfMemory
exception.
There are huge collections used in my project and by changing one parameter I can make my program to be more accurate or use less of the memory...
OK, that's the background. What I would like to do is to run the routines in a loop:
OutOfMemory
exception, change the parameter and try to run it again.Now, I would like to test it. I know, that I can throw the OutOfMemory
exception on my own, but I would like to simulate some real situation.
So the main question is:
Is there a way of setting some kind of memory limit for my program, after reaching which the OutOfMemory
exception will be thrown automatically?
For example, I would like to set a limit, let's say 400MB of memory for my whole program to simulate the situation when there is such an amount of memory available in the system.
Can it be done?
Well, according to the topic of the question, best way to avoid out of memory exception would be not to create objects that fill in that memory. Then you can calculate the length of your queue based on estimate of one object memory capacity. Another way would be to check for memory size in each worker thread.
When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.
OutOfMemoryError exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further.
To simulate OutOfMemoryError , we could simply keep adding objects to a Java Collection such as LinkedList in a loop, until the JVM runs out of the heap memory and throws this error. In the example below, the infinite loop will add a new object of size 10MB on each iteration until it runs of memory.
This looks like a job for...System.Runtime.MemoryFailPoint.
http://msdn.microsoft.com/en-us/library/system.runtime.memoryfailpoint.aspx
I think the example in the link fits your situation. Set the MemoryFailPoint to whatever level you need and then catch the InsufficientMemoryException and adjust your input parameters accordingly.
public void EatMemory()
{
List<byte[]> wastedMemory = new List<byte[]>();
while(true)
{
byte[] buffer = new byte[4096]; // Allocate 4kb
wastedMemory.Add(buffer);
}
}
Shouldn't take long unless you've got 12gb of ram :)
Just allocate a very large array. You'll most likely start getting out of memory exceptions once your C# application reaches 1.2-1.6GB of RAM usage (usually on the lower side of that range, provided its targetting x86).
string value = new string('crazy', int.MaxValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With