0

From a naive point of view, it looks like declaring a local variables (ie., variables inside a method) as "final" could cause memory leak.

Eg.,

public static MyObject create()
{

     final Long time = System.millis();
     return new MyObject()
     {
           @Override public Long getTime() {return "Time is: " + time ; }
     }
}

Clearly, the time field has to be kept around even when create() has returnt in order for getTime() to work.

Ok, now say I have this method

public static int create()
{

    final Long time = System.millis();
    System.out.println(time);
    return 2;     
}

time is not referenced in any inner class. Is the object kept around after the method returns? Y

Thanks,

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
One Two Three
  • 22,327
  • 24
  • 73
  • 114
  • the *value* has to be kept around (how else would the returned object function). What do you mean when you say that the *variable* or *field* is kept around? – aioobe Oct 31 '14 at 14:28

2 Answers2

4

The object you are returning stores the value it has to return. I wouldn't call this a memory leak, as this is what you intended the code to do. A memory leak is an undesirable waste of memory.

A more significant potential for memory leak is if you make the method non-static. In this case a reference to the outer class is retained and all it's data even though you clearly don't need it.

Is the object kept around after the method returns?

The object can be cleaned up after it is passed to println(). When/if it is cleaned up depends on the GC, but this is not considered a memory leak.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Right, I can see that. In the example I gave, it is right to keep `time` around. BUT say I didn't have the anonymous class object, would the variable be kept around? – One Two Three Oct 31 '14 at 14:24
  • @OneTwoThree Can you give a specific example, as in general it will do the right thing? – Peter Lawrey Oct 31 '14 at 14:31
1

In your case, there is an anonymous Class created by compiler and this class reference to has a Field that implicitly reference to Long object instance (that referenced by 'time' variable).

The memory of Long Object that referenced by 'time' variable is ON Java Heap memory. This Long object memory will have the same lifecycle with the instance of Anonymous created. SO -- No memory leak here.

For Case2: Long object memory will exists for a while even the 'create' method is DONE because this memory is on Heap. This memory will not destroyed until Next Garbage Collector run ------- SO No memory leak here.

NOTE:

I am answering in general case. In the real world. Long Object can be POOLED if its value from -127 to 128. In this case Long Object that referenced by variable 'time' may have the same Lifecycle with Your whole application (JVM instance)

LHA
  • 9,398
  • 8
  • 46
  • 85