How Can I Get Ehcache To Keep Heap Size Bytes Statistics For Unbounded Caches?

不想你离开。 提交于 2019-12-05 08:56:30

I'm beginning to think what I'm asking for isn't possible with Ehcache (at least the version I'm on)

Here is the pool config in the source for net.sf.ehcache.Cache.class:

// on-heap pool configuration
Pool onHeapPool;
if (configuration.getMaxBytesLocalHeap() > 0) {
    PoolEvictor evictor = new FromLargestCachePoolEvictor();
    SizeOfEngine sizeOfEngine = cacheManager.createSizeOfEngine(this);
    onHeapPool = new BoundedPool(configuration.getMaxBytesLocalHeap(), evictor, sizeOfEngine);
} else if (getCacheManager() != null && getCacheManager().getConfiguration().isMaxBytesLocalHeapSet()) {
    onHeapPool = getCacheManager().getOnHeapPool();
} else {
    onHeapPool = new UnboundedPool();
}

Later on a net.sf.ehcache.store.MemoryStore is created from this pool, using net.sf.ehcache.store.MemoryStore.MemoryStore(Ehcache, Pool, BackingFactory, SearchManager). The following lines create the net.sf.ehcache.pool.PoolAccessor:

if (pool instanceof UnboundedPool) {
    this.poolAccessor = pool.createPoolAccessor(null, null);
} else {
    this.poolAccessor = pool.createPoolAccessor(new Participant(),
        SizeOfPolicyConfiguration.resolveMaxDepth(cache),
        SizeOfPolicyConfiguration.resolveBehavior(cache).equals(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT));
}

Since the pool is an UnboundedPool (no heap size was specified), the PoolAccessor is created without a net.sf.ehcache.pool.SizeOfEngine, but more importantly the type is net.sf.ehcache.pool.impl.UnboundedPool.UnboundedPoolAccessor. The add method for this type does not track size, while the type of PoolAccessor that's created for for a bounded pool does. (see net.sf.ehcache.pool.impl.AbstractPoolAccessor.add(Object, Object, Object, boolean)).

So, I'm out of luck in terms of Ehcache having a setting that I can use, however there is a hacky way to achieve this solution if, like myself, you are seeking an unbounded cache. The below will keep track of memory stats as they are added, but will allow unbounded additions to the cache:

<cache name="myCache"
    timeToIdleSeconds="1800"
    memoryStoreEvictionPolicy="LRU"
    overflowToDisk="false"
    overflowToOffHeap="false"
    maxBytesLocalHeap="1">
    <pinning store="inCache" />
</cache>

@butallmj: adding a pinning store to your cache instance negates the memoryStoreEvictionPolicy. So any item added to your cache will always remain in memory even though you use it or not. Instead i would suggest to provide bounds using maxBytesLocalHeap configuration to the defined cache.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!