通用 InternPool在Java中?
我如何用 Java 编写通用的 InternPool
?它需要一个Internable接口吗?
Java中的String
具有interning能力;我想实习 BigDecimal
和 Account
等类。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
像这样的事情:
这取决于池元素类实现
equals
和hashCode
来提供“按值相等”并遵守这些方法的API契约。但 BigDecimal 确实如此。更新 - 解释为什么我们需要
WeakHashMap>
而不是WeakHashMap
,请参阅 javadocs。简而言之,后者的关键薄弱环节不会被 GC 破坏,因为相应的条目引用使值具有很强的可达性。Something like this:
This depends on the pool element class implementing the
equals
andhashCode
to provide "equality by value" and to obey to the API contracts for those methods. ButBigDecimal
certainly does.UPDATE - for an explanation of why we need a
WeakHashMap<T, WeakReference<T>>
rather than aWeakHashMap<T, T>
, see the javadocs. The short version is that the key weak-links in the latter won't be broken by the GC because the corresponding entry references are making the values strongly reachable.有关示例,请查看
Interner
来自 Guava。它不需要需要Internable
接口,它只依赖于equals
和hashCode
。For an example take a look at
Interner
from Guava. It does not require anInternable
interface, it just relies onequals
andhashCode
.这听起来更像是您正在寻找 flyweight 模式。
单击链接,它包含一个 Java 示例。
This more sounds like that you're looking for flyweight pattern.
Click the link, it contains a Java example.
我会将解决方案分成两个类,以获得更清晰的代码,并且通过这种方式摆脱循环:
并且使用弱池的实习类非常简单:
I would separate the solution into two classes to have cleaner code and also this way getting rid of loop:
and the interning class using the weak pool is very simple:
只是一个快速警告:
上面没有明确提到,但很明显,被保留的对象必须是不可变类型。
第二个注意事项:您不需要使用对该对象的另一个弱引用作为映射中的值,如果您仅依赖映射的键集来获取数据,则对静态的引用就足够了。例如,声明:
并将对插入为:
这是对 WeakReference 实例的少量节省(如果您无法重用用于键的实例)。
...或者创建一个 WeakSet 类,就像 @PeterVerhas 对他的 WeakPool 所做的那样。
Just a quick caveat:
It has not been explicitly mentioned above, but it should be obvious that the objects being interned must be of an immutable type.
On a second note: You don't need to use another weak reference to the object as the value in the map, a reference to a static would suffice if you just rely on the map's keyset for the data. For example, declare:
And insert pairs as:
Which is a minor saving of a WeakReference instance (if you can't reuse the one used for the key).
...or create a WeakSet class, as @PeterVerhas has done with his WeakPool.
不应该
“WeakReference ref = pool.get(object);”
相反,
WeakReference ref = pool.intern(object);
??
Shouldnt
"WeakReference ref = pool.get(object);"
instead be
WeakReference ref = pool.intern(object);
??