声明变量final和static [英] Declaring variable final and static

查看:121
本文介绍了声明变量final和static的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此评论是在代码审核中完成的,而制作该评论的人已不在我们的团队中。

This comment was made in a code review and the person who made it is no longer on our team.


在运行时必须由类加载器解析的任何类型都不应该具有被声明为final和static的引用保持的实例。

Any type that must be resolved by the classloader at runtime should never have instances which are held by references declared to be both final and static.

以下是代码行:

private final static Logger log = LoggerFactory.getLogger(MyClass.class);

我熟悉声明loggers静态或非静态的争论,但这个评论似乎是更一般。我找不到任何关于为什么静态和最终都不好的解释。有人可以详细说明吗?

I'm familiar with the debate of declaring loggers static or non-static, but this comment seems to be more general. I can't find any explanations of why static and final are bad. Can somebody elaborate?

推荐答案

评论很可能与 Classloader Leaking (< a href =http://java.jiderhamn.se/2012/02/26/classloader-leaks-v-common-mistakes-and-known-offenders/ =noreferrer>这里有一篇好文章)。

简而言之,这个问题发生在需要重新加载类加载器的环境中。如果通过类加载器动态加载类,然后尝试重新加载类加载器,则使用通过此类加载器创建的类的对象保留静态最终字段将阻止卸载类加载器本身。一旦发生这种情况,您将获得 OutOfMemoryError

In a nutshell, this problem happens in environments where classloader needs to be reloaded. If you load a class dynamically through a classloader and then try reloading the classloader, keeping static final fields with objects of classes created through this classloader will prevent unloading the classloader itself. Once this happens, you get an OutOfMemoryError.

上面链接的文章列出了可能产生此行为的主要罪魁祸首之间的日志库,以及可以解决泄漏问题的措施(例如明确释放类加载器) 。

The article linked above lists logging libraries among the top culprits that could produce this behavior, along with measures you can take to work around the leaks (such as releasing classloaders explicitly).

这篇关于声明变量final和static的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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