在Java中缓存和重用不可变单例对象的最佳方式是什么? [英] What is the best way to cache and reuse immutable singleton objects in Java?
问题描述
这个类是不可变的,我想使它成为一个单独的每个不同的值都使用静态工厂模式。
目标是防止相同的对象创建多次(100+)次并优化equals方法。
我正在寻找最佳方法缓存并重用此类的以前的实例。
首先想到的是一个简单的hashmap,但是有其他选择吗?
有两种情况:
- 如果不同对象的数量很小并且是固定的,那么应该使用
enum
在使用模式中,您可以选择仅缓存最后一个 N 实例,而不是迄今为止创建的所有实例。这是用于例如 re.compile
在Python的正则表达式模块中。如果 N 足够小(例如5),那么使用线性搜索的简单数组也可以正常工作。
对于<$ c基于$ c> Map 的解决方案,或许一个有用的实现是 java.util.LinkedHashMap
,它允许您在 @时执行类似LRU的策略覆盖
removeEldestEntry
。
还有 LRUMap $ c $ Apache Commons Collections 更直接地实施此政策。
另见
相关的问题
-
li> LRU LinkedHashMap基于可用内存限制大小 - 番石榴
MapMaker
,软键和值等 - 如何在Java 6中实现LRU缓存?
I have a class representing a set of values that will be used as a key in maps.
This class is immutable and I want to make it a singleton for every distinct set of values, using the static factory pattern. The goal is to prevent identical objects from being created many (100+) times and to optimize the equals method.
I am looking for the best way to cache and reuse previous instances of this class. The first thing that pops to mind is a simple hashmap, but are there alternatives?
There are two situations:
- If the number of distinct objects is small and fixed, you should use an
enum
- They're not instantiatiable beyond the declared constants, and
EnumMap
is optimized for it
- They're not instantiatiable beyond the declared constants, and
- Otherwise, you can cache immutable instances as you planned:
Depending on the usage pattern, you may choose to only cache, say, the last N instances, instead of all instances created so far. This is the approach used in e.g. re.compile
in Python's regular expression module. If N is small enough (e.g. 5), then a simple array with a linear search may also work just fine.
For Map
based solution, perhaps a useful implementation is java.util.LinkedHashMap
, which allows you to enforce LRU-like policies if you @Override
the removeEldestEntry
.
There is also LRUMap
from Apache Commons Collections that implement this policy more directly.
See also
- Java Tutorials/
enums
- Effective Java 2nd Edition, Item 1: Consider static factory methods instead of constructors
- Wikipedia/Flyweight pattern
Related questions
- Easy, simple to use LRU cache in java
- LRU LinkedHashMap that limits size based on available memory
- Guava
MapMaker
, soft keys and values, etc
- Guava
- How would you implement an LRU cache in Java 6?
这篇关于在Java中缓存和重用不可变单例对象的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!