使用Class实例作为Map键是最佳实践吗? [英] Is using the Class instance as a Map key a best practice?

查看:75
本文介绍了使用Class实例作为Map键是最佳实践吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读过如下使用类实例并不是一个好主意,因为它们可能会导致内存泄漏。有人可以告诉我,如果这是一个有效的声明?或者这样使用它有什么问题吗?

I have read somewhere that using the class instances as below is not a good idea as they might cause memory leaks. Can someone tell me if if that is a valid statement? Or are they any problems using it this way?

Map<Class<?>,String> classToInstance = new HashMap();

classToInstance.put(String.class,"Test obj");


推荐答案

是的,你需要谨慎!例如,如果您的代码在Web容器中运行,并且您习惯于对Web应用程序进行热部署,则对单个类对象的保留引用可能会导致严重的permgen内存泄漏。

Yes, you do need to be cautious! For example, if your code is running in a web container and you are in the habit of doing hot deployment of webapps, a retained reference to a single class object can cause a significant permgen memory leak.

这篇文章解释问题详细。但简而言之,问题是每个类都包含对其类加载器的引用,并且每个类加载器都包含对它已加载的每个类的引用。因此,如果一个类可以访问,则所有类都是。

This article explains the problem in detail. But in a nutshell, the problem is that each class contains a reference to its classloader, and each classloader contains references to every class that it has loaded. So if one class is reachable, all of them are.


来自Java 8 - Permgen去掉了。您认为在任何情况下都可以将Class实例用作HashMap键吗?

From Java 8 - Permgen was removed. Do you think it is ok to use Class instance as HashMap key in any situations?

请注意,您仍会有内存泄漏。您的HashMap(键或值)和(至少)其他动态加载的类中使用的任何动态加载的类都将保持可访问状态。这意味着GC将无法卸载/删除它们。之前的permgen泄漏现在是普通的堆泄漏。

Be aware that you will still have a memory leak. Any dynamicly loaded class used in your HashMap (key or value) and (at least) other dynamically loaded classes will be kept reachable. This means the GC won't be able to unload / delete them. What was previously a permgen leak is now an ordinary heap leak.

这篇关于使用Class实例作为Map键是最佳实践吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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