문제

Suppose I write a program which creates a lot of String objects and intern() them:

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

This is fine for a small set of strings but what if I try to create a billion Strings? (or billion * billion for that matter?) As far as I know the JVM maintains a constant pool in the PermGen area for Strings and PermGen does not get GC-ed.

So if I create an excessive number of String objects in a loop but I drop the references to them will they get GC-ed (will I run out of PermGen space)? The Strings are all unique without any duplications.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top