2

假设我编写了一个程序,它创建了很多String对象和intern()它们:

String someString = param1 + param2;
someString.intern();

这对于一小组字符串来说很好,但是如果我尝试创建十亿个Strings 怎么办?(或十亿 * 十亿?)据我所知,JVM在PermGen区域为s维护一个常量池,而PermGen没有得到GCString

因此,如果我在循环中创建了过多的String对象,但我删除了对它们的引用,它们会得到GC吗(我会用完PermGen空间吗)?Strings 都是唯一的,没有任何重复。

4

2 回答 2

8

In Java 6, you can fill the PermGen and it will be cleaned up.

In Java 7, interned strings are not in PermGen, but in the heap.

In Java 8, there is no PermGen.

Literal pools, only contain constants and if you create a new String, it is not a literal so it is not in the pool in the first place.

Note: the String literal hash map doesn't resize. It is typically around 10K elements by default. As you add entries it get slower and slower as it turns into an array of linked lists.

于 2013-10-03T19:11:48.363 回答
3

No. What you're showing is not the literal syntax.

String myString = "a literal String";

Would be the literal syntax. However you can make sure all your Strings are put in the constant pool with the String.intern() method. You can test yourself what happens when you intern an excess amount of Strings.

于 2013-10-03T19:11:23.910 回答