views:

50

answers:

2
     if(pCoeff.size()>thisCoeff.size()){
        difference=pCoeff.size()-thisCoeff.size();
        for(int i=thisCoeff.size(); i<thisCoeff.size()+difference;i++){

            thisCoeff.add(i, new Double(0.0)); //this line throws errors
        }
     } 

I've isolated this portion of my program as being the cause of memory leak, is it possible to patch this using a try catch statement? If so, what is the syntax?

+4  A: 

is it possible to patch this using a try catch statement?

In general, no.

However, I think I can see the cause of your problem. Basically, tbe loop will never terminate. Each time you go around the loop, you add a new object to the collection. This increases the value returned by thisCoeff.size() by one. The following fix addresses this:

if (pCoeff.size() > thisCoeff.size()) {
    difference = pCoeff.size() - thisCoeff.size();
    int limit = thisCoeff.size() + difference;
    for (int i = thisCoeff.size(); i < limit; i++) {
        thisCoeff.add(i, new Double(0.0));
    }
}
Stephen C
It works perfectly now, thank you.
@user481211 please accept this answer then (click the checkmark).
matt b
A: 

No, the only way to do that is to have something become unreachable in the catch statement than can then be garbage collected.

In this case, assuming that the .size() methods don't do anything unexpected, the memory usage comes from all of those double objects, you can gain a huge memory improvement by using only one Double object as a static constant, and adding it to the collection, or letting the jvm autobox for you.

Yishai