This question has baffled myself and my cohorts. In the program I had written I was experiencing a memory leak. The var Platform, was being reassigned each iterations to a new object. But for some reason the old platform objects where not being cleaned by the gc and after many iterations the heap overflows:
Some of you may realise this is a PSO algorithm. But for those who don’t this function has to be evaluated 1000’s of times, and basicplatform is an extremely data extensive object, so multiple instances would eventually give a memory overflow, just to give a little context.
Buggy code:
public class Fitness implements FitnessFunction{
protected Platform platform;
public Fitness(){
}
public Fitness(Platform platform) {
this.platform = platform;
}
@Override
public double fitness(Particle p) {
try {
platform = new BasicPlatform("testData.csv");
} catch (Exception e) {
e.printStackTrace();
}
platform.startSimulation();
double prof = platform.getFitness();
v.clear();
if(prof != 0)
return -prof;
return 0;
}
}
After being confused as to why there is leak, as surely there shoudln’t be, my friend showed me this solution, which he used before in a similar situation:
public class TradingRuleFitness implements FitnessFunction{
protected Platform platform;
public Fitness(){
}
public Fitness(Platform platform) {
this.platform = platform;
}
@Override
public double fitness(Particle p) {
Vector<Platform> v = new Vector<Platform>();
try {
//platform = new BasicPlatform("testData.csv");
v.add(new BasicPlatform("testData.csv"));
} catch (Exception e) {
e.printStackTrace();
}
double prof = v.get(0).getFitness;
v.clear();
if(prof != 0)
return -prof;
return 0;
}
}
Nearly exactly the same but this time instead of re-assigning the var platform we create a new object inside a vector and delete it after I have finished with it.This method seems to force the gc into cleaning up.
The question is why does this vector method work but not the original which technically should and are there any cleaner solutions?
p.s I have cleaned up unnesscary bits of code, as the question is about the object creation and removal
In the first case, if your Fitness object si retained, so will your Platform object be retained as it a field.
In the second case, your Platform is held in a local variable and is discard when
fitnessreturns.It doesn’t have to be a Vector, it could be a plain local variable.
Try removing the field in both examples and it should work either way.