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

查看:237
本文介绍了在 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 运算符在堆上创建对象.然后将引用附加到它们.如果引用变为空或超出范围(例如,块结束),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天全站免登陆