I am facing some problems with garbage collection while generating an application in java, where I use Stream.map to trim all the elements in the list. The instances of anonymous lambda class exist in the heap dump even though the instance of the enclosing class is 0 as shown in the snap of visual VM.
The LambdaTesting class:
class LambdaTesting {
protected List<String> values;
protected LambdaTesting(List<String> values) {
this.values = values;
}
public List<String> modify() {
return this.values.stream().map(x -> x.trim()).collect(Collectors.toList());
}
public List<String> modifyLocal() {
List<String> localValue = new ArrayList<>();
localValue.add("Local FOO ");
localValue.add("Local BAR ");
return localValue.stream().map(x -> x.trim()).collect(Collectors.toList());
}
}
The method which creates the instance of LambdaTesting and invokes these methods:
public List<String> testMethods() {
List<String> test = new ArrayList<>();
test.add("Global FOO ");
test.add(" GLOBAL BAR");
LambdaTesting lambdaTesting = new LambdaTesting(test);
lambdaTesting.modifyLocal();
lambdaTesting.modify();
}
The thread dump was taken after putting a debug point at the next line after testMethods is invoked.
Why are the references to Lambda still present in the heap dump?