如果字符串池的大小超过怎么办? [英] What if Size of String Pool Exceeds?

查看:236
本文介绍了如果字符串池的大小超过怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,

String Constant Pool中的字符串文字不是垃圾收集的,
因为它们是从实例创建的引用表中引用的运行时以优化空间。

String literals in String Constant Pool are not garbage collected, since they are referenced from Table of references which is created by instance of runtime in order to optimize space.

如果字符串文字池的大小超过,则
由于字符串文字池中的每个字符串都有引用,因此它将没有资格获得GC。
如何由JVM处理?

推荐答案

与实际代码示例进行了长时间的讨论 JavaRanch

There is a long discussion with real code examples at JavaRanch.

一般输出如下:


  1. 如果在RUNTIME使用字符串添加到常量池中String.intern(),可以在不再使用后收集垃圾。最有可能的是,字符串池仅保留对添加的字符串的软引用,因此允许对它们进行垃圾收集(不能确定,因为String.intern()是本机方法)。

  2. 如果字符串是COMPILE时间常量,则将其添加到相应类的常量池中。因此,只有在卸载类后才可以对其进行垃圾回收。

  1. If a string is added to constant pool at RUNTIME using String.intern(), it can be garbage collected after it is no longer in use. Most probably, the string pool keeps only soft references to added strings, thus allowing to garbage collect them (can't be sure, because String.intern() is a native method).
  2. If a string is a COMPILE time constant, it is added to the constant pool of the corresponding class. Therefore, it can be garbage collected only after the class is unloaded.

您的问题的答案是:唯一的方法是得到OutOfMemoryError因为String常量是加载很多类,在编译时计算了很多字符串文字。然后,您最终可以超过PermGen空间的最大大小。但是,这会在您将类加载到内存中时发生(例如,启动应用程序,将项目部署到WebServer,动态加载新库等)。

The answer to your question is: the only way how you can get OutOfMemoryError because of String constants is to load lot's of classes with many string literals computed at compile time. Then you can eventually exceed maximum size of PermGen space. But this will happen at the time you load classes into memory (e.g., start your application, deploy project to a WebServer, dynamically load new library, etc.)

这篇关于如果字符串池的大小超过怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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