Memory leak using autoboxing

pjj :

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.

GhostCat salutes Monica C. :

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:

  • as long as there is a single (strong!) reference to the map object from another object that is "alive" in GC terms, that map is "alive". And therefore: all objects stored within that map are alive (not eligible for GC)
  • when the last reference to that map vanishes, the map itself becomes eligible for the GC. Same is true for the values within the map - unless there is some other reference to such a value which is still alive.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473282&siteId=1