Java Caching System (JCS) – How to use it

The Java Caching System (JCS) is a robust open source caching product released through the Apache Jakarta subproject. It provides the standard features that you would expect of a cache system, such as in-memory caching and algorithms for selectively removing objects from the cache. It also offers more-advanced features, such as indexed disk caching and support for distributed caches.

It is a good alternative to EHCache and Redis. As per their claims, they are twice as faster than EHCache.

You can download JCS from here : JCS Download. It has a core jar which needs to be included in our build path. It is also dependent on commons-logging jar. So include that also in your class path.

Let’s see the sample code which demonstrates the usage of this library. It basically creates objects of Movie class and puts them in the cache which are removed/retrieved later on. Before moving to code have a look at the config file where we can configure various properties of JCS

# DEFAULT CACHE REGION
jcs.default=DC
jcs.default.cacheattributes=
org.apache.jcs.engine.CompositeCacheAttributes
jcs.default.cacheattributes.MaxObjects=1000
jcs.default.cacheattributes.MemoryCacheName=
org.apache.jcs.engine.memory.lru.LRUMemoryCache
jcs.default.cacheattributes.UseMemoryShrinker=true
jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=3600
jcs.default.cacheattributes.ShrinkerIntervalSeconds=60
jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
jcs.default.elementattributes.IsEternal=false
jcs.default.elementattributes.MaxLifeSeconds=21600
jcs.default.elementattributes.IdleTime=1800
jcs.default.elementattributes.IsSpool=true
jcs.default.elementattributes.IsRemote=true
jcs.default.elementattributes.IsLateral=true

So using this config file we define multiple regions with different properties. You might want to have different cache regions for different kind of objects in your application. By default JCS will look for this cache.ccf file in the classpath. But we can also load these values in the Properties and pass them to JCS. In that case JCS will not look for the file.

So here is the code :

package Cache;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
 
import org.apache.commons.jcs.JCS;
import org.apache.commons.jcs.access.CacheAccess;
import org.apache.commons.jcs.access.exception.CacheException;
import org.apache.commons.jcs.engine.control.CompositeCacheManager;
 
public class JCSExample
{
    private CacheAccess<Integer, Object> cache;
 
    public JCSExample()
    {
        try
        {
        	CompositeCacheManager ccm = CompositeCacheManager.getUnconfiguredInstance(); 
        	Properties props = new Properties(); 
        	try {
				props.load(new FileInputStream(new File("C:\\Downloads\\workspace\\SampleProject\\src\\Cache\\cache.ccf")));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	//JCS.defineRegion("default");
            // Load the cache
        	ccm.configure(props);
            cache = JCS.getInstance( "default" );
 
            // Initialize the cache
            cache.put( new Integer( 1 ),
                 new Movie( 1, "Dangal" ) );
            cache.put( new Integer( 2 ),
                 new Movie( 2, "3 Idiots") );
            cache.put( new Integer( 3 ),
                 new Movie( 3, "Rang de basanti") );
        }
        catch( CacheException e )
        {
            e.printStackTrace();
        }
    }
 
    public void addAlbum( Movie album )
    {
        try
        {
            cache.put( album.getId(), album );
        }
        catch( CacheException e )
        {
            e.printStackTrace();
        }
    }
 
    public Movie getMovie( Integer id )
    {
        return ( Movie )cache.get( id );
    }
 
    public void removeMovie( Integer id )
    {
        try
        {
            cache.remove( id );
        }
        catch( CacheException e )
        {
            e.printStackTrace();
        }
    }
 
    public static void main( String[] args )
    {
        JCSExample musicStore = new JCSExample();
        musicStore.addAlbum( new Movie( 4, "Taare zameen pe") );
        Movie album = musicStore.getMovie( 1 );
        System.out.println( "Movie 1: " + album.getName() );
        album = musicStore.getMovie( 4 );
        System.out.println( "Movie 4: " + album.getName() );
        musicStore.removeMovie( 4 );
        album = musicStore.getMovie( 4 );
        System.out.println( "Movie 4: " + album );
    }
}
 
class Movie{
	int id;
 
	public Movie(int i, String name) {
		this.id = i;
		this.name = name;
	}
 
	public int getId() {
		return id;
	}
 
	public void setId(int id) {
		this.id = id;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	String name;
 
 
}

Output of above code would be :

Movie 1: Dangal
Movie 4: Taare zameen pe
Movie 4: null

Mar Java Mit Java 🙂

Uday Ogra

Connect with me at http://facebook.com/tendulkarogra and lets have some healthy discussion :)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *