[英]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. data
是某类的属性。
Every time the method gets called, a new Integer
is replacing the currently existing data
reference. 每次调用该方法时, new Integer
都将替换当前存在的data
引用。 So what's happening with the current/old data? 那么当前/旧数据发生了什么?
Java has to be doing something under the hood; Java必须在幕后做点什么; 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. 请注意,您的方法根本不会创建新的Integer
对象。 A reference to the same Integer
object could be passed in time and time again, for example. 例如,可以一次又一次地传递对同一个Integer
对象的引用。
The reality of garbage collection is a lot more complicated than this: 垃圾收集的现实比这复杂得多:
Java is a garbage-collected language. Java是一种垃圾收集语言。
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. 简而言之,您的代码是100%正确的,并没有泄漏内存。
最终会收集垃圾。
如果没有对data
引用,java的垃圾收集器将清理旧数据并释放内存
Actually, since Integer is an object not a primitive type, the line: 实际上,由于Integer是一个非原始类型的对象,因此该行:
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. 现在,GC将检查this.data
过去指向的旧对象,以确定是否没有更多对该对象的引用。 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. GC在后台由Java执行以释放未使用对象的内存。
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. 最初,我再次将x分配给10个x到20的第一个参考内存将由Java GC处理。 Java GC is a thread tht run continuously and checked unreferenced memory and clean it . Java GC是一个连续运行的线程,检查未引用的内存并清理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.