OSCache源码阅读(二)

前文LRU Cache 暨LinkedHashMap源码阅读提到了如何使用LinkedHashMap来实现一个LRU数据结构,,今天在看OSCache代码算法部分的时候,就用到了该知识,what was done contributes what is done now。

algorithm包是包含下列缓存过期策略的类:

下面重点介绍LRU和FIFO。

LRUprivate Collection list = new LinkedHashSet();

使用一个LinkedHashSet对象来实现LRU,而LinkedHashSet的父类是HashSet,

public 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.** @paraminitialCapacity the initial capacity of the linked hash set* @paramloadFactorthe load factor of the linked hash set* @throwsIllegalArgumentException 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{serialVersionUID = -10333778645392679L;/*** A queue containing all cache keys*/private Collection list = new LinkedHashSet();

底层也是用LinkedHashSet来存储key的……也比较好理解了。

擒龙要下海,打虎要上山。

OSCache源码阅读(二)

相关文章:

你感兴趣的文章:

标签云: