可以使用太多静态变量导致Java中的内存泄漏吗? [英] Can using too many static variables cause a memory leak in Java?

查看:1485
本文介绍了可以使用太多静态变量导致Java中的内存泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的应用程序有太多静态变量或方法,那么根据定义,它们将存储在堆中。如果我错了请纠正我

If my application has too many static variables or methods, then as per definition they will be stored in heap. Please correct me if I am wrong

1)在应用程序关闭之前,这些变量是否会在堆上?

2)它们是否可用于GC随时?如果没有,我可以说它是内存泄漏吗?

1) Will these variables be on heap until application is closed?
2) Will they be available for GC at any time? If not can I say it is a memory leak?

推荐答案

静态方法只是方法,它们不存储在堆上,他们只是不使用this参数。

Static methods are just methods, they are not stored on the heap, they just don't get to use a "this" parameter.

静态变量充当GC的根。因此,除非您明确地将它们设置为null,否则只要程序存在,它们就会存在,所以从它们可以到达的所有内容也是如此。

Static variables serve as "roots" to the GC. As a result, unless you explicitly set them to null, they will live as long as the program lives, and so is everything reachable from them.

只考虑一种情况如果你打算让内存变得空闲并且它不会被释放,那么内存泄漏。如果您打算让静态变量在某个时间内包含对象的引用,并且在完成该对象时忘记将其设置为null,则可能最终会出现泄漏。但是,如果你把它放在静态变量中并且打算在程序运行时它就在那里,那么它绝对不是泄漏,它更可能是一个永久单例。如果对象在你希望它仍然存在时被回收,那将是非常糟糕的。

A situation is only considered a memory leak if you intend for the memory to become free and it doesn't become free. If you intend for your static variable to contain a reference to an object for part of the time, and you forget to set it to null when you're done with that object, you would likely end up with a leak. However, if you put it in the static variable and intend for it to be there for as long as the program is running, then it is most definitely not a leak, it is more likely a "permanent singleton". If the object got reclaimed while you wanted it to still exist, that would have been very bad.

关于堆的问题:Java中的所有对象都存在于堆上或堆栈上。使用new运算符在堆上创建对象。然后将引用附加到它们。如果引用变为null或超出范围(例如,块结束),则GC意识到无法再次到达该对象并回收它。如果您的引用是静态变量,它永远不会超出范围,但您仍然可以将其设置为null或另一个对象。

As for your question about the heap: All objects in Java exist either on the heap or on the stack. Objects are created on the heap with the new operator. A reference is then attached to them. If the reference becomes null or falls out of scope (e.g., end of block), the GC realizes that there is no way to reach that object ever again and reclaims it. If your reference is in a static variable, it never falls out of scope but you can still set it to null or to another object.

这篇关于可以使用太多静态变量导致Java中的内存泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆