Strings are immutable and are managed in String pool. I wish to know as how this pool is managed. If there are large number of String literals being used in an application, ( I understand String builder should be used when modifications like append, replace operations are more ) then Pool enhances the performance of the application by not recreating the new String objects again and again but using the same objects present in the pool, this is possible as Strings are immutable and doing so has no ill effect.
My question is as how this String Pool
is managed. If in case there is huge frequency of some 'k' Strings and there may be few other String objects which are once created and not being used again. There may be other newer String literals being used.
In cases like these does String Pool behaves like LRU cache, holding the references to the latest used literals and removing the older not used strings from the pool ?
Does String pool has a size or can we control it in our application ?
Edit :
Usually we give size to the custom object pools we implement. I wonder why feature like LRU is not there for Sting Pools. This could have been a feature. In case of large Strings also there would not have been problem. But I feel its the way it has been implemented but I just wanted to know as why its not there, I mean its not there for some valid reason, having this feature would have resulted in some ill effects. If some one could throw some light on those ill effects, it will be good.
答案 0 :(得分:3)
字符串池不是LRU缓存,因为除非使用GC,否则不会删除条目。
有两种方法可以在String池中获取条目。字符串文字自动转到那里,并且可以使用String.intern()
添加新条目,除非池中已存在String
,在这种情况下会返回对它的引用。
如果没有更多对它们的引用,则 垃圾收集,对于字符串文字(例如字符串常量)可能比intern()
ed更难。 / p>
Java 6和Java 8(甚至是次要版本之间)的实现发生了很大变化。字符串池的默认大小显然是1009
,但可以使用-XX:StringTableSize=N
(自Java 7起)参数进行更改。这个大小是内部哈希表的表大小,所以如果你使用了很多intern()
它可以调高(对于字符串文字,它应该很多)。大小仅影响intern()
调用的速度,而不影响您可以实习的字符串数量。
除非你大量使用intern()
(大概是有充分理由),否则几乎没有理由担心字符串池。特别是因为它不再存储在PermGen
中,所以它不再容易导致OutOfMemoryErrors
。