Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Assignment Memory Leaks

I have to assume that the following method doesn't leak memory:

public final void setData(final Integer p_iData)
{
    data = p_iData;
}

Where data is a property of some class.

Every time the method gets called, a new Integer is replacing the currently existing data reference. So what's happening with the current/old data?

Java has to be doing something under the hood; otherwise we'd have to null-out any objects every time an object is assigned.

like image 386
IAmYourFaja Avatar asked Oct 04 '11 18:10

IAmYourFaja


People also ask

Can a Java program expose a memory leak?

A small Java application might have a memory leak, but it will not matter if the JVM has enough memory to run your program. However, if your Java application runs constantly, then memory leaks will be a problem. This is because a continuously running program will eventually run out of memory resources.

How do you identify memory leaks in Java?

Using Java VisualVM With Java VisualVM, we can memory-monitor the Java Heap and identify if its behavior is indicative of a memory leak.

What could be the possible cause of memory leaks in Java?

Causes of Memory LeaksUsing Unwanted Object Reference: These are the object references that are no longer needed. The garbage collector is failed to reclaim the memory because another object still refers to that unwanted object. Using Long-live Static Objects: Using static objects also leads to a memory leak.


2 Answers

Simplistic explanation:

Periodically the garbage collector looks at all the objects in the system, and sees which aren't reachable any more from live references. It frees any objects which are no longer reachable.

Note that your method does not create a new Integer object at all. A reference to the same Integer object could be passed in time and time again, for example.

The reality of garbage collection is a lot more complicated than this:

  • Modern GCs tend to be generational, assuming that most objects are short-lived, so it doesn't need to check the whole (possibly large) heap as often; it can just check "recent" objects for liveness frequently
  • Objects can have finalizers - code to be run before they're garbage collected. This delays garbage collection of such objects by a cycle, and the object could even "resurrect" itself by making itself reachable
  • Modern GCs can collect in parallel, and have numerous tweaking options
like image 63
Jon Skeet Avatar answered Sep 22 '22 10:09

Jon Skeet


Java is a garbage-collected language.

Once there are no more live references to an object, it becomes eligible for garbage collection. The collector runs from time to time and will reclaim the object's memory.

In a nutshell, your code is 100% correct and is not leaking memory.

like image 42
NPE Avatar answered Sep 18 '22 10:09

NPE