简体   繁体   中英

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.

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

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.

最终会收集垃圾。

如果没有对data引用,java的垃圾收集器将清理旧数据并释放内存

Actually, since Integer is an object not a primitive type, the line:

data = p_iData;

is updating a reference.

Now, the old object that this.data used to point to will be examined by the GC to determine if there are no more references to that object. If not, that object is destroyed and the memory is freed (at some later time)

If the object previously referenced by data is no longer referenced by any object structure that is referenced from any running thread it is eligible for garbage collecion. GC is performed by Java in the background to free the memory of unused objects.

i want to show one example to you in some code :

int x;
x=10;
x=20;

initially i assigned x to 10 again x to 20 first reference memory will be handled by Java GC. Java GC is a thread tht run continuously and checked unreferenced memory and clean it .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM