OSCache源码阅读(二)
前文LRU Cache 暨LinkedHashMap源码阅读提到了如何使用LinkedHashMap来实现一个LRU数据结构,今天在看OSCache代码算法部分的时候,就用到了该知识,what was done contributes what is done now。
algorithm包是包含下列缓存过期策略的类:
下面重点介绍LRU和FIFO。
LRU
private Collection list = new LinkedHashSet();
使用一个LinkedHashSet对象来实现LRU,而LinkedHashSet的父类是HashSet,
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
private static final long serialVersionUID = -2851667679971038690L;
/**
* Constructs a new, empty linked hash set with the specified initial
* capacity and load factor.
*
* @param initialCapacity the initial capacity of the linked hash set
* @param loadFactor the load factor of the linked hash set
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
/**
* Constructs a new, empty linked hash set with the specified initial
* capacity and the default load factor (0.75).
*
* @param initialCapacity the initial capacity of the LinkedHashSet
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true);
}
/**
* Constructs a new, empty linked hash set with the default initial
* capacity (16) and load factor (0.75).
*/
public LinkedHashSet() {
super(16, .75f, true);
}
/**
* Constructs a new linked hash set with the same elements as the
* specified collection. The linked hash set is created with an initial
* capacity sufficient to hold the elements in the specified collection
* and the default load factor (0.75).
*
* @param c the collection whose elements are to be placed into
* this set
* @throws NullPointerException if the specified collection is null
*/
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
}
其中,HaseSet的构造器之一是:
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
通过LinkedHashMap来实现的。
所以LRU的实现就容易理解了。
FIFO
public class FIFOCache extends AbstractConcurrentReadCache {
private static final long serialVersionUID = -10333778645392679L;
/**
* A queue containing all cache keys
*/
private Collection list = new LinkedHashSet();
底层也是用LinkedHashSet来存储key的……也比较好理解了。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。