常量池(JVM JDK 6)中的“a”vs'new String(“b”)'(渴望真相) [英] “a” vs 'new String(“b”)' in Constant Pool (JVM JDK 6) (eager for the truth)

查看:136
本文介绍了常量池(JVM JDK 6)中的“a”vs'new String(“b”)'(渴望真相)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道a new String(b)都会创建ab在常量池

i know "a" and new String("b") both will create "a"or "b" in constant pool

但为什么以下程序不抛出 outOfMemoryError

But why the following program doesn't throw outOfMemoryError?

new String(b)在常量池中创建任何东西

Does new String("b") create nothing in constant pool?

List<String> s = new ArrayList<String>();
// -XX:PermSize=5M
// -XX:MaxPermSize=5M
// why no oom:pergen space throw???? "i" isn't in constant pool????
for (;;) {
    for (int i = 0; i < 1000000; i++) {
        s.add(new String("" + i));
    }
}


推荐答案

新String(...)正在正常堆中创建对象,因此限制永久生成将不会触发OOME。
对于较旧版本的java,您可以通过在结果字符串上调用.intern()来对其进行模拟,但即使最近也有所改变(请阅读 http://java-performance.info/string-intern-in-java-6-7-8/ 详细信息)。

new String(...) is creating object in normal heap, so limiting permanent generation won't fire off OOME. With older version of java you could simulate it by calling .intern() on resulting string, but even that has changed recently (please read http://java-performance.info/string-intern-in-java-6-7-8/ for details).

在java 8中,发电似乎完全消失
http://www.infoq.com/articles/Java-PERMGEN-Removed
所以除非你专门针对旧版本,否则可能会适得其反,试图找到它限制,而是尝试了解Metaspace。

In java 8, perm generation seems to be completely gone http://www.infoq.com/articles/Java-PERMGEN-Removed so unless you specifically target older versions, it might be counterproductive trying to find its limits and instead try to understand Metaspace.

这篇关于常量池(JVM JDK 6)中的“a”vs'new String(“b”)'(渴望真相)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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