天天看点

Java Cache-EHCache系列之Store实现

写了那么多,终于到store了。store是ehcache中element管理的核心,所有的element都存放在store中,也就是说store用于所有和element相关的处理。

ehcache中的element

在ehcache中,它将所有的键值对抽象成一个element,作为面向对象的设计原则,把数据和操作放在一起,element除了包含key、value属性以外,它还加入了其他和一个element相关的统计、配置信息以及操作:

public class element implements serializable, cloneable {

    //the cache key. 从1.2以后不再强制要求serializable,因为如果只是作为内存缓存,则不需要对它做序列化。ignoresizeof注解表示在做sizeof计算时key会被忽略。

    @ignoresizeof

    private final object key;

    //the value. 从1.2以后不再强制要求serializable,因为如果只是作为内存缓存,则不需要对它做序列化。

    private final object value;

    //version of the element. 这个属性只是作为纪录信息,ehcache实际代码中并没有用到,用户代码可以通过它来实现不同版本的处理问题。默认值是1。

    //如果net.sf.ehcache.element.version.auto系统属性设置为true,则当element加入到cache中时会被更新为当前系统时间。此时,用户设置的值会丢失。

    private volatile long version;

    //the number of times the element was hit.命中次数,在每次查找到一个element会加1。

    private volatile long hitcount;

    //the amount of time for the element to live, in seconds. 0 indicates unlimited. 即一个element自创建(creationtime)以后可以存活的时间。

    private volatile int timetolive = integer.min_value;

    //the amount of time for the element to idle, in seconds. 0 indicates unlimited. 即一个element自最后一次被使用(min(creationtime,lastaccesstime))以后可以存活的时间。

    private volatile int timetoidle = integer.min_value;

    //pluggable element eviction data instance,它存储这个element的creationtime、lastaccesstime等信息,窃以为这个抽取成一个单独的类没什么理由,而且这个类的名字也不好。

    private transient volatile elementevictiondata elementevictiondata;

    //if there is an element in the cache and it is replaced with a new element for the same key, 

    //then both the version number and lastupdatetime should be updated to reflect that. the creation time

    //will be the creation time of the new element, not the original one, so that ttl concepts still work. 在put和replace操作中该属性会被更新。

    private volatile long lastupdatetime;

    //如果timetolive和timetoidle没有手动设置,该值为true,此时在计算expired时使用cacheconfiguration中的timetilive、timetoidle的值,否则使用element自身的值。

    private volatile boolean cachedefaultlifespan = true;

    //这个id值用于ehcache内部,但是暂时不知道怎么用。

    private volatile long id = not_set_id;

    //判断是否expired,这里如果timetolive、timetoidle都是integer.min_value时返回false,当他们都是0时,iseternal返回true

    public boolean isexpired() {

        if (!islifespanset() || iseternal()) {

            return false;

        }

        long now = system.currenttimemillis();

        long expirationtime = getexpirationtime();

        return now > expirationtime;

    }

    //expirationtime算法:如果timetoidle没有设置,或设置了,但是该element还没有使用过,取timetolive计算出的值;如果timetolive没有设置,则取timetoidle计算出的值,

    //否则,取他们的最小值。

    public long getexpirationtime() {

            return long.max_value;

        long expirationtime = 0;

        long ttlexpiry = elementevictiondata.getcreationtime() + timeutil.tomillis(gettimetolive());

        long mostrecenttime = math.max(elementevictiondata.getcreationtime(), elementevictiondata.getlastaccesstime());

        long ttiexpiry = mostrecenttime + timeutil.tomillis(gettimetoidle());

        if (gettimetolive() != 0 && (gettimetoidle() == 0 || elementevictiondata.getlastaccesstime() == 0)) {

            expirationtime = ttlexpiry;

        } else if (gettimetolive() == 0) {

            expirationtime = ttiexpiry;

        } else {

            expirationtime = math.min(ttlexpiry, ttiexpiry);

        return expirationtime;

    //在将element加入到cache中并且它的timetolive和timetoidle都没有设置时,它的timetolive和timetoidle会根据cacheconfiguration的值调用这个方法更新。

    protected void setlifespandefaults(int tti, int ttl, boolean eternal) {

        if (eternal) {

            this.timetoidle = 0;

            this.timetolive = 0;

        } else if (iseternal()) {

            this.timetoidle = integer.min_value;

            this.timetolive = integer.min_value;

            timetoidle = tti;

            timetolive = ttl;

}

public class defaultelementevictiondata implements elementevictiondata {

    private long creationtime;

    private long lastaccesstime;

public class cache implements internalehcache, storelistener {

    private void applydefaultstoelementwithoutlifespanset(element element) {

        if (!element.islifespanset()) {

            element.setlifespandefaults(timeutil.converttimetoint(configuration.gettimetoidleseconds()),

                    timeutil.converttimetoint(configuration.gettimetoliveseconds()),

                    configuration.iseternal());

ehcache中的store设计

store是ehcache中用于存储、管理所有element的仓库,它抽象出了所有对element在内存中以及磁盘中的操作。基本的它可以向一个store中添加element(put、putall、putwithwriter、putifabsent)、从一个store获取一个或一些element(get、getquiet、getall、getallquiet)、获取一个store中所有key(getkeys)、从一个store中移除一个或一些element(remove、removeelement、removeall、removewithwriter)、替换一个store中已存储的element(replace)、pin或unpin一个element(unpinall、ispinned、setpinned)、添加或删除storelistener(addstorelistener、removestorelistener)、获取一个store的element数量(getsize、getinmemorysize、getoffheapsize、getondisksize、getterracottaclusteredsize)、获取一个store的element以byte为单位的大小(getinmemorysizeinbytes、getoffheapsizeinbytes、getondisksizeinbytes)、判断一个key的存在性(containskey、containskeyondisk、containskeyoffheap、containskeyinmemory)、query操作(setattributeextractors、executequery、getsearchattribute)、cluster相关操作(iscachecoherent、isclustercoherent、isnodecoherent、setnodecoherent、waitutilclustercoherent)、其他操作(dispose、getstatus、getmbean、hasabortedsizeof、expireelements、flush、bufferfull、getinmemoryevictionpolicy、setinmemoryevictionpolicy、getinternalcontext、calculatesize)。

所谓cache,就是将部分常用数据缓存在内存中,从而提升程序的效率,然而内存大小毕竟有限,因而有时候也需要有磁盘加以辅助,因而在ehcache中真正的store实现就两种(不考虑分布式缓存的情况下):存储在内存中的memorystore和存储在磁盘中的diskstore,而所有其他store都是给予这两个store的基础上来扩展store的功能,如因为内存大小的限制,有些时候需要将内存中的暂时不用的element写入到磁盘中,以腾出空间给其他更常用的element,此时就需要memorystore和diskstore共同来完成,这就是frontcachetier做的事情,所有可以结合frontendcachetier一起使用的store都要实现tierablestore接口(diskstore、memorystore、nullstore);对于可控制store占用空间大小做限制的store还可以实现poolablestore(diskstore、memorystore);对于具有terracotta特性的store还实现了terracottastore接口(transactionstore等)。

ehcache中store的设计类结构图如下:

Java Cache-EHCache系列之Store实现

abstractstore

几乎所有的store实现都继承自abstractstore,它实现了query、cluster等相关的接口,但没有涉及element的管理,而且这部分现在也不了解,不详述。

memorystore和notifyingmemorystore

memorystore是ehcache中存储在内存中的element的仓库。它使用selectableconcurrenthashmap作为内部的存储结构,该类实现参考concurrenthashmap,只是它加入了pinned、evict等逻辑,不详述(注:它的setpinned方法中,对不存在的key,会使用一个dummy_pinned_element来创建一个节点,并将它添加到hashentry的链中,这时为什么?窃以为这个应该是为了在以后这个key添加进来后,当前的pinned设置可以对它有影响,因为memorystore中并没有包含所有的element,还有一部分element是在diskstore中)。而memorystore中的基本实现都代理给selectableconcurrenthashmap,里面的其他细节在之前的文章中也有说明,不再赘述。 

而notifyingmemorystore继承自memorystore,它在element evict和exipre时会调用注册的cacheeventlistener。

diskstore

diskstore依然采用concurrenthashmap的实现思想,因而这部分逻辑不赘述。对diskstore,当一个element添加进来后,需要将其写入到磁盘中,这是接下来关注的重点。在diskstore中,一个element不再以element本身而存在,而是以disksubstitute的实例而存在,disksubstitute有两个子类:placeholder和diskmarker,当一个element初始被添加到diskstore中时,它是以placeholder的形式存在,当这个placeholder被写入到磁盘中时,它会转换成diskmarker。

    public abstract static class disksubstitute {

        protected transient volatile long onheapsize;

        @ignoresizeof

        private transient volatile diskstoragefactory factory;

        disksubstitute(diskstoragefactory factory) {

            this.factory = factory;

        abstract object getkey();

        abstract long gethitcount();

        abstract long getexpirationtime();

        abstract void installed();

        public final diskstoragefactory getfactory() {

            return factory;

    final class placeholder extends disksubstitute {

        private final object key;

        private final element element;

        private volatile boolean failedtoflush;

        placeholder(element element) {

            super(diskstoragefactory.this);

            this.key = element.getobjectkey();

            this.element = element;

        @override

        public void installed() {

            diskstoragefactory.this.schedule(new persistentdiskwritetask(this));

    public static class diskmarker extends disksubstitute implements serializable {

        private final long position;

        private final int size;

        private volatile long hitcount;

        private volatile long expiry;

        diskmarker(diskstoragefactory factory, long position, int size, element element) {

            super(factory);

            this.position = position;

            this.size = size;

            this.hitcount = element.gethitcount();

            this.expiry = element.getexpirationtime();

            //no-op

        void hit(element e) {

            hitcount++;

            expiry = e.getexpirationtime();

当向diskstore添加一个element时,它会先创建一个placeholder,并将该placeholder添加到diskstore中,并在添加完成后调用placeholder的installed()方法,该方法会使用diskstoragefactory schedule一个persistentdiskwritetask,将该placeholder写入到磁盘(在diskstoragefactory有一个diskwriter线程会在一定的时候执行该task)生成一个diskmarker,释放placeholder占用的内存。在从diskstore移除一个element时,它会先读取磁盘中的数据,将其解析成element,然后释放这个element占用的磁盘空间,并返回这个被移除的element。在从diskstore读取一个element时,它需要找到diskstore中的disksubstitute,对diskmarker读取磁盘中的数据,解析成element,然后返回。 

frontendcachetier 

上述的memorystore和diskstore,他们是各自独立的,然而cache的一个重要特点是可以将部分内存中的数据evict出到磁盘,因为内存毕竟是有限的,所以需要有另一个store可以将memorystore和diskstore联系起来,这就是frontendcachetier做的事情。frontendcachetier有两个子类:diskbackedmemorystore和memoryonlystore,这两个类的名字已经能很好的说明他们的用途了,diskbackedmemorystore可以将部分element先evict出到磁盘,它也支持把磁盘文件作为persistent介质,在下一次读取时可以直接从磁盘中的文件直接读取并重新构建原来的缓存;而memoryonlystore则只支持将element存储在内存中。frontendcachetier有两个store属性:cache和authority,它将基本上所有的操作都直接同时代理给这两个store,其中把authority作为主的存储store,而将cache作为缓存的store。在diskbackedmemorystore中,authority是diskstore,而cache是memorystore,即diskbackedmemorystore将diskstore作为主的存储store,这刚开始让我很惊讶,不过仔细想想也是合理的,因为毕竟这里的disk是作为persistent介质的;在memoryonlystore中,authority是memorystore,而cache是nullstore。

frontendcachetier在实现get方法时,添加了faults属性的concurrenthashmap,它是用于多个线程在同时读取同一key的element时避免多次读取,每次之前将key和一个fault新实例添加到faults中,这样第二个线程发现已经有另一个线程在读这个element了,它就可以等待第一个线程读完直接拿第一个线程读取的结果即可,以提升性能。

所有作为frontendcachetier的内部store都必须实现tierablestore接口,其中fill、removeifnotpinned、istierpinned、getpresentpinnedkeys为cache store准备,而removenoreturn、ispersistent为authority store准备。

public interface tierablestore extends store {

    void fill(element e);

    boolean removeifnotpinned(object key);

    void removenoreturn(object key);

    boolean istierpinned();

    set getpresentpinnedkeys();

    boolean ispersistent();

lrumemorystore和legacystorewrapper

这两个store只是为了兼容而存在,其中lrumemorystore使用linkedhashmap作为其存储结构,他只支持一种evict算法:lru,这个store的名字也因此而来,其他功能它类似memorystore,而legacystorewrapper则类似frontendcachetier。这两个store的代码比较简单,而且他们也不应该再被使用,因而不细究。 

terraccottastore

对所有实现这个接口的store都还不了解,看以后有没有时间回来了。。。。