I was following tutorial and below was the example for auto boxing memory leak.
package com.example.memoryleak;
public class Adder {
public long addIncremental(long l) {
Long sum=0L;
sum =sum+l;
return sum;
}
public static void main(String[] args) {
Adder adder = new Adder();
for(long ;i<1000;i++) {
adder.addIncremental(i);
}
}
}
Now, I could understand that unnecessary objects would be created because of autoboxing but how it caused memory leak, the way I understand is that memory leak is caused when you are holding a strong reference to a dead object. Now, in this case once I have came out of the FOR loop there would be no strong references to those Long
objects then how it caused memory leak?
Please note I want to understand how it caused memory leak, I know those objects were unnecessary.
The other answers are correct: this is not a memory leak.
The code you are showing creates object on a very high rate; and they are subject to garbage collection immediately. None of of these "temp" objects is somehow forgotten; they all get eligible for collection; and the GC will collect them at some point.
A memory leak refers to situations where the used memory keeps ever increasing - without the objects ever becoming eligible for garbage collection.
Given the comment that asks about the "cache" example that uses a map:
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