Java 的 String Intern 是轻量级的吗? [英] Is Java's String Intern a flyweight?

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

问题描述

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

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

我之所以有这个疑问,是因为我看到 Intern 并没有涉及外在状态.在 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.

或者我们应该说没有关于属性的严格规则,仅仅共享对象以减少内存就足以称其为享元.

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.

请帮我理解.

推荐答案

与实习无关,Java 字符串利用享元模式通过在字符串和从它派生的字符串之间共享 char[] 通过 substring 和类似的方法调用.不过,这也有一个反面:如果你从一个巨大的字符串中取出一个小的子字符串,那么巨大的 char[] 将没有资格进行垃圾回收.

Irrespective of interning, Java String utilizes the flyweight pattern by sharing the char[] between a string and those derived from it via substring and similar method calls. This has a flipside, though: if you take a small substring of a huge string, the huge char[] will not be eligible for garbage collection.

注意: 自 OpenJDK 1.7.0_06 版起,上述内容已过时:代码已更改,因此 char[] 不再在实例之间共享.substring() 创建一个新数组.

Note: as of OpenJDK version 1.7.0_06 the above has become obsolete: the code was changed so that the char[] is no longer shared between instances. substring() creates a new array.

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

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