Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak using autoboxing

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.

like image 874
pjj Avatar asked May 17 '17 12:05

pjj


1 Answers

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.
like image 139
GhostCat Avatar answered Sep 18 '22 18:09

GhostCat