Java的String Intern是一个flyweight吗? [英] Is Java's String Intern a flyweight?

查看:140
本文介绍了Java的String Intern是一个flyweight吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的String内存池的实现是否遵循flyweight模式?

Does the implementation of Java's String memory pool follows flyweight pattern?

为什么我有这个疑问,我看到实习中没有涉及外部状态。在GoF中,我读到内在和外在状态之间应该有一个平衡。但是在实习生中,一切都是内在的。

Why I have this doubt is, I see that there is no extrinsic state involved in Intern. In GoF I read that there should be a right balance between intrinsic and extrinsic state. But in intern everything is intrinsic.

或者我们说没有关于属性的严格规则,只是共享对象来减少内存就足以称之为flyweight。

Or shall we say there is no strict rule with respect to attributes and just sharing objects to reduce memory is sufficient to call it a flyweight.

请帮助我理解。

推荐答案

$ c> String.intern()实现遵循flyweight模式。

Yes the String.intern() implementation follows the flyweight pattern.

作为 javadoc

返回字符串对象的规范表示。
字符串的池,最初为空,由类String私有地维护。

Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.

当调用intern方法时,如果池已经包含
字符串等于由equals(Object)
方法确定的此String对象,则返回池中的字符串。否则,此
String对象被添加到池中,并返回对此String
对象的引用。

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

因此,对于任何两个字符串s和t,s.intern()== t.intern()
当且仅当s.equals(t)为真时为true。

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

所有文字字符串和字符串值常量表达式都是
。字符串文字在Java语言
规范的§3.10.5中定义。

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

内部字符串驻留在 空格和由 .intern()返回的字符串对象可以使用运算符 == ,因为 .intern()对于相等的值返回始终是相同的对象。

The internalized strings reside in the "Perm Gen" space and on string objects returned by .intern() you can use the operator == because .intern() returns always the same object for equal values.

然后记住 .intern() 方法不会产生泄漏,因为今天的JVM可以无用池。

Then remember that .intern() method does not produce leaks, because the JVM today is able garbage the pool.

尝试阅读这个文章

这篇关于Java的String Intern是一个flyweight吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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