About Cache Eviction Algorithms

A cache eviction algorithm is a way of deciding which element to evict when the cache is full. In Ehcache , the memory store and the off-heap store might be limited in size. When these stores get full, elements are evicted. The eviction algorithms determine which elements are evicted. The default algorithm is Least Recently Used (LRU).

What happens on eviction depends on the cache configuration. If a disk store is configured, the evicted element is flushed to disk; otherwise it is removed. The disk store size by default is unbounded. But a maximum size can be set as described in “Sizing the Storage Tiers” in the Configuration Guide for Ehcache . If the disk store is full, then adding an element causes an existing element to be evicted.

Note: The disk store eviction algorithm is not configurable. It uses LFU.

Built-in Memory Store Eviction Algorithms

The idea here is, given a limit on the number of items to cache, how to choose the thing to evict that gives the best result.

In 1966 Laszlo Belady showed that the most efficient caching algorithm would be to always discard the information that will not be needed for the longest time in the future. This is a theoretical result that is unimplementable without domain knowledge. The Least Recently Used (LRU) algorithm is often used as a proxy. In general, it works well because of the locality of reference phenomenon and is the default in most caches.

A variation of LRU is the default eviction algorithm in Ehcache .

Ehcache provides three eviction algorithms to choose from for the memory store.

Least Recently Used (LRU)

This is the default and is a variation on the Least Frequently Used algorithm.

The oldest element is the Less Recently Used element. The last-used timestamp is updated when an element is put into the cache or an element is retrieved from the cache with a get call.

This algorithm takes a random sample of the Elements and evicts the smallest. Using the sample size of 15 elements, empirical testing shows that an Element in the lowest quartile of use is evicted 99% of the time.

If probabilistic eviction does not suit your application, a true Least Recently Used deterministic algorithm is available by setting java -Dnet.sf.ehcache.use.classic.lru=true.

Least Frequently Used (LFU)

For each get() call on the element, the number of hits is updated. When a put() call is made for a new element (and assuming that the max limit is reached), the element with least number of hits (the Least Frequently Used element) is evicted.

If cache-element usage follows a Pareto distribution, this algorithm might give better results than LRU.

LFU is an algorithm unique to the Ehcache API. It takes a random sample of the Elements and evicts the smallest. Using the sample size of 15 elements, empirical testing shows that an Element in the lowest quartile of use is evicted 99% of the time.

First In First Out (FIFO)

Elements are evicted in the same order as they come in. When a put call is made for a new element (and assuming that the max limit is reached for the memory store) the element that was placed first (first-in) in the store is the candidate for eviction first-out.

This algorithm is used if the use of an element makes it less likely to be used in the future. An example here would be an authentication cache.

It takes a random sample of the Elements and evicts the smallest. Using the sample size of 15 elements, empirical testing shows that an Element in the lowest quartile of use is evicted 99% of the time.

Plugging in Your own Eviction Algorithm

Ehcache allows you to plug in your own eviction algorithm using Cache.setMemoryStoreEvictionPolicy(Policy policy). You can utilize any Element metadata, which makes possible some very interesting approaches. For example, you might evict an element if it has been hit more than ten times.

/**
* Sets the eviction policy strategy. The Cache will use a policy at startup.
* There are three policies which can be configured: LRU, LFU and FIFO. However
* many other policies are possible. That the policy has access to the whole
* element enables policies based on the key, value, metadata, statistics, or a
* combination of any of the above.
*
* It is safe to change the policy of a store at any time. The new policy takes
* effect immediately.
*
* @param policy the new policy
*/
public void setMemoryStoreEvictionPolicy(Policy policy) {
  memoryStore.setEvictionPolicy(policy);
}

A Policy must implement the following interface:

/**
* An eviction policy.
* <p/>
* The Cache will use a policy at startup. There are three policy implementations provided in ehcache:
* LRU, LFU and FIFO. However many other policies are possible. That the policy
* has access to the whole element enables policies based on the key, value, metadata, statistics, or a combination of
* any of the above.
*
* @author Greg Luck
*/
public interface Policy { /**
* @return the name of the Policy. Inbuilt examples are LRU, LFU and FIFO.
*/
String getName(); /**
* Finds the best eviction candidate based on the sampled elements. What distinguishes
* this approach from the classic data structures approach is that an Element contains
* metadata (e.g. usage statistics) which can be used for making policy decisions,
* while generic data structures do not. It is expected that implementations will take
* advantage of that metadata.
*
* @param sampledElements this should be a random subset of the population
* @param justAdded we probably never want to select the element just added.
* It is provided so that it can be ignored if selected. May be null.
* @return the selected Element
*/
Element selectedBasedOnPolicy(Element[] sampledElements, Element justAdded); /**
* Compares the desirableness for eviction of two elements
*
* @param element1 the element to compare against
* @param element2 the element to compare
* @return true if the second element is preferable for eviction to the first element
* under ths policy
*/
boolean compare(Element element1, Element element2);
}

Disk Store Eviction Algorithm

The disk store uses the Least Frequently Used algorithm to evict an element when the store it is full.

Ehcache(2.9.x) - API Developer Guide, Cache Eviction Algorithms的更多相关文章

  1. Ehcache(2.9.x) - API Developer Guide, Cache Loaders

    About Cache Loaders A CacheLoader is an interface that specifies load() and loadAll() methods with a ...

  2. Ehcache(2.9.x) - API Developer Guide, Cache Event Listeners

    About Cache Event Listeners Cache listeners allow implementers to register callback methods that wil ...

  3. Ehcache(2.9.x) - API Developer Guide, Cache Decorators

    About Cache Decorators Ehcache uses the Ehcache interface, of which Cache is an implementation. It i ...

  4. Ehcache(2.9.x) - API Developer Guide, Cache Usage Patterns

    There are several common access patterns when using a cache. Ehcache supports the following patterns ...

  5. Ehcache(2.9.x) - API Developer Guide, Cache Manager Event Listeners

    About CacheManager Event Listeners CacheManager event listeners allow implementers to register callb ...

  6. Ehcache(2.9.x) - API Developer Guide, Cache Exception Handlers

    About Exception Handlers By default, most cache operations will propagate a runtime CacheException o ...

  7. Ehcache(2.9.x) - API Developer Guide, Cache Extensions

    About Cache Extensions Cache extensions are a general-purpose mechanism to allow generic extensions ...

  8. Ehcache(2.9.x) - API Developer Guide, Write-Through and Write-Behind Caches

    About Write-Through and Write-Behind Caches Write-through caching is a caching pattern where writes ...

  9. Ehcache(2.9.x) - API Developer Guide, Searching a Cache

    About Searching The Search API allows you to execute arbitrarily complex queries against caches. The ...

随机推荐

  1. Google中rel="canonical"的相关解释和用法

    转载原地址 http://blog.sina.com.cn/s/blog_673b01740100jxlz.html 近听到很多SEO 对在页面的规范版本用规范 URL 标签( canonical U ...

  2. HDU 4461 The Power of Xiangqi (水题)

    题意:给定一些字母,每个字母都代表一值,如果字母中没有B,或者C,那么就在总值大于1的条件下删除1,然后比较大小. 析:没什么好说的,加起来比较就好了. 代码如下: #pragma comment(l ...

  3. Spring的ControllerAdvice注解

    @ControllerAdvice,是spring3.2提供的新注解,其实现如下所示: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUN ...

  4. SQL中DATE和DATETIME类型不能直接作比较

    如题,今天纠结了一天的问题. 在存储过程中定义了两个datetime类型的时间,然后把这个两个时间作为where条件中一个date字段between的两个时间段,结果无论如何都不执行... 就像  u ...

  5. C++成员变量、构造函数的初始化顺序

    一.C++成员变量初始化 1.普通的变量:一般不考虑啥效率的情况下 可以在构造函数中进行赋值.考虑一下效率的可以再构造函数的初始化列表中进行 2.static 静态变量(本地化数据和代码范围): st ...

  6. [0.0]Analysis of Baidu search engine

    Rencently, my two teammates and I is doing a project, a simplified Chinese search engine for childre ...

  7. windows 下实现函数打桩:拦截API方式

    windows 下实现函数打桩:拦截API方式            近期由于工作须要,開始研究函数打桩的方法. 由于不想对project做过多的改动,于是放弃了使用Google gmock的想法. ...

  8. Codeforces Round #172 (Div. 2) B. Nearest Fraction 二分

    B. Nearest Fraction Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/281/p ...

  9. [置顶] VC++界面编程之--自定义CEdit(编辑框)皮肤

    自定义编辑框是登陆界面经常用到的效果,所以我也模仿站酷网的素材做了个. 要想继承CCustomDraw来完全自绘CEdit控件,是不太可行的方案,因为一旦你完全重绘,那么你需要额外做以下几件事: 1. ...

  10. WPF UI布局之概述

    在线演示:http://v.youku.com/v_show/id_XNzA5NDk2Mjcy.html 清晰版视频+代码下载:http://115.com/lb/5lbeer0m9lad 一.简单介 ...