Menu

Home

Alan N. Lohse

Cachelet

version 1.0.0_b1

Cachelet is a cache framework created thinking on the simplest way of caching. So it is very easy to use.

Start caching

The example below shows how to create a read and write cache.

        CacheFactory factory = CacheFactory.createCacheFactory();
        Cache<Integer, String> cache = factory.createCache();
        // first populate some values
        cache.put(Integer.valueOf(1), "One");       
        cache.put(Integer.valueOf(20), "Twenty");       
        cache.put(Integer.valueOf(300), "Three hundred");       
        cache.put(Integer.valueOf(4123), "Four thousand one hundred and twenty three");
        // get the values
        cache.get(1);

Building a cache

There's a easy way to configure a cache. Using the builder you can easily change all properties without need to know property keys. And methods have very intuitive names.

        CacheFactory factory = CacheFactory.createCacheFactory();
        Cache<String,User> cache = factory.buildCache()
                .setMaxObjectsOnMemory(20)
                .build();

Cache with object factory

The cached objects can be created as they are needed and you don't have to worry about putting things on cache. The way it canbe done is by using an object factory.

        ObjectFactory<String,User> myObjectFactory = new ObjectFactory<String,User>() {
                    public User create(String key) {
                        return findOnDatabase((String)key);
                    }
                };

        Cache<String,User> cache = factory.buildCache().setObjectFactory(myObjectFactory)
                .setMaxObjectsOnMemory(20)
                .build();

Cleaning old objects

Objects that stood long in the cache without use, can be removed using cleaning algorithms. The most common are LRU (Least Recently Used) and LFU (Least Frequently Used) and Cachelet have both implemented (having enough time I'll create more).
There are some ways to tell Cachelet that objects should be removed:
1. by providing an expiration time;
2. by limiting the number of objects on memory;
3. by providing a expiration policy.

In this first example I'll set a clean interval, it's the time that the algorithm will check the objects on cache. There's something important when we setup a cleaning algorithm, a parallel thread will be created for each cleaner.

        Cache<String,Integer> cache = factory.buildCache()
                .setObjectFactory(myObjectFactory)
                .setExpireTime(0)
                .setCleanInterval(500L)
                .setMaxObjectsOnMemory(20)
                .setCleanAlgorithm(Cache.LFU)
                .build();

Very easy, isn't it?

Project Members: