Simple Java caching library or design pattern?

断了今生、忘了曾经 提交于 2019-12-04 02:08:09
Brian Agnew

Congratulations for realising that writing your own can be more trouble it initially appears!

I would check out the Guava cache solution. Guava is a proven library and the caches are easily available (and configurable) via a fluent factory API.

All Guava caches, loading or not, support the method get(K, Callable<V>). This method returns the value associated with the key in the cache, or computes it from the specified Callable and adds it to the cache. No observable state associated with this cache is modified until loading completes. This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern.

I would suggest for you to use the Proxy Design Pattern that way you can encapsulate the caching logic-implementation in your proxy class

theres a cool example here that looks like to fit your needs

http://en.wikipedia.org/wiki/Proxy_pattern

tjg184

I would take a look at Google guava-libraries. Much of this work has already been done for you.

There's specifically a section called Timed Eviction, which might be related to what you want. https://github.com/google/guava/wiki/CachesExplained#timed-eviction

Ramesha.C

if you do not want to use third party library, simply you can create a static map which holds the key and value. using key you can retrieve the data fast.

and write methods to add values to cache, get, remove.

public SimpleCache{
    private static Map<String,Object> simpleCache = new HashMap<>();

    public static <T> T getValue(String key, Class type){

    //todo check contains here, if map doesn't contains key, throw not found exception

    Object val = simpleCache.get(key);

    return (T)val;    
  }
}

hope this helps

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