Java固定内存映射 [英] Java fixed memory map
问题描述
有没有一个简单,高效的地图
实现,可以让地图使用内存限制。
我的用例是我想在创建时动态分配大部分可用的内存,但我将来不会在任何时候使用
OutOFMemoryError
。基本上,我想使用这个地图作为缓存,但是我想避免像 EHCache
这样的重缓存实现。我的需求很简单(最多是一个LRU算法) 我应该进一步澄清,缓存中的对象是 char []
或类似的原语,不会保留对其他对象的引用。
我可以为每个条目的最大大小设置上限。
因为jasonmp85指出LinkedHashMap有一个允许访问顺序的构造函数。当我查看API文档时,我错过了这一点。实施也看起来很有效率(见下文)。结合每个条目的最大大小上限,这应该可以解决我的问题。
我还将密切关注SoftReference。只是为了纪录,Google Collections似乎对SoftKeys和SoftValues和Maps一般都有相当不错的API。
这是Java LikedHashMap类的一个代码段,显示了它们如何维护LRU行为。
/ **
*从链表中删除此条目。
* /
private void remove(){
before.after = after;
after.before = before;
}
/ **
*在列表中指定的现有条目之前插入此条目。
* /
private void addBefore(Entry< K,V> existingEntry){
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
/ **
*只要事先存在的条目的值
*被Map.get读取或修改,该方法将被超类调用通过Map.set。
*如果封闭的地图是访问订单,它将条目
*移动到列表的末尾;否则,它什么都不做。
* /
void recordAccess(HashMap< K,V> m){
LinkedHashMap< K,V> lm =(LinkedHashMap< K,V>)m;
if(lm.accessOrder){
lm.modCount ++;
remove();
addBefore(lm.header);
}
Is there a simple, efficient Map
implementation that allows a limit on the memory to be used by the map.
My use case is that I want to allocate dynamically most of the memory available at the time of its creation but I don't want OutOFMemoryError
at any time in future. Basically, I want to use this map as a cache, but but I wanna avoid heavy cache implementations like EHCache
. My need is simple (at most an LRU algorithm)
I should further clarify that objects in my cache are char[]
or similar primitives that will not hold references to other objects.
I can put an upper limit on max size for each entry.
thanks for replies guys!
As jasonmp85 pointed out LinkedHashMap has a constructor that allows access order. I missed out that bit when I looked at API docs. The implementation also looks quite efficient(see below). Combined with max size cap for each entry, that should solve my problem.
I will also look closely at SoftReference. Just for the record, Google Collections seems to have pretty good API for SoftKeys and SoftValues and Maps in general.
Here is a snippet from Java LikedHashMap class that shows how they maintain LRU behavior.
/**
* Removes this entry from the linked list.
*/
private void remove() {
before.after = after;
after.before = before;
}
/**
* Inserts this entry before the specified existing entry in the list.
*/
private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
/**
* This method is invoked by the superclass whenever the value
* of a pre-existing entry is read by Map.get or modified by Map.set.
* If the enclosing Map is access-ordered, it moves the entry
* to the end of the list; otherwise, it does nothing.
*/
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
这篇关于Java固定内存映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!