Reputation: 2716
I am writing a code in java, where an integer type variable m receives its value from the user and this value is used to allocate memory (exponentially) to an array.
for example:
int m=29;
int [] c = new int [(int)pow(2,m)];
My question is How can I check if it is possible to allocate memory according to the above code before actual allocation takes place and throw an exception to the user in case it is not possible either due to
java.lang.OutOfMemoryError: Java heap space
or due to
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Also I would like to know that how can I overcome the memory limitation where the memory requirement changes exponentially (eg. 2^m) within program.
Upvotes: 0
Views: 794
Reputation:
The answer I think you are looking for is Runtime.freeMemory()
- http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#freeMemory()
This may be helpful in some cases to scale your solution to the available memory. In practice, however, you still want to wrap the memory call in a try-catch like:
int m=29;
int [] c = null;
try {
c = new int [(int)pow(2,m)];
} catch(OutOfMemoryError e) {
//Try with less memory?
//Other error handling?
}
Upvotes: 1
Reputation: 35051
There are two ways. The first is you can use Runtime(.getRuntime()).freeMemory() to get the size of available memory. Your array is going to be sizeof(int) (ie 4) * 2^whatever. So you can check that. I don't know where you can get the VM array size limit (the information is probably available somewhere, or can be obtained through testing) but you can do something similar with this.
The other (easier) way is to put this in a try {} catch block, and catch the Errors. In general, it is not recommended to catch Errors, but in this case it might make some sense.
Upvotes: 0