JCS – Setting different max life and idle time for different elements

We have already seen how to use JCS – Java caching system.
We usually have a property file which defines the various properties of the cache like maximum age, maximum idle time etc. But this is at cache level. What if we want to have different max age for different elements being inserted into the same cache?

JCS has a way to set these properties explicitly for each element. In the following code Movie 1 has default max age, movie 2 has max age of 3 seconds and movie 3 again has the default max age.

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.behavior.IElementAttributes;
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" ) );
 
            //set max life as 3 seconds
            IElementAttributes attrs = cache.getDefaultElementAttributes();
            long oldMaxLife = attrs.getMaxLife();
            attrs.setMaxLife(3);
            cache.setDefaultElementAttributes(attrs);
            cache.put( new Integer( 2 ),
                 new Movie( 2, "3 Idiots") );
 
            //set max life to default value as read from config file
            attrs.setMaxLife(oldMaxLife);
            cache.setDefaultElementAttributes(attrs);
            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") );
        try {
			Thread.sleep(4*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Movie album = musicStore.getMovie( 1 );
        System.out.println( "Movie 1: " + album );
        album = musicStore.getMovie( 2 );
        System.out.println( "Movie 2: " + album );
        album = musicStore.getMovie( 3 );
        System.out.println( "Movie 3: " + album );
        album = musicStore.getMovie( 4 );
        System.out.println( "Movie 4: " + album );
        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;
 
 
}

The output of above program would be:

Movie 1: Cache.Movie@53bd815b
Movie 2: null
Movie 3: Cache.Movie@4926097b
Movie 4: Cache.Movie@762efe5d
Movie 4: null

As expected Movie 1 will remain in the cache as its max age is default, which means eternal. Movie 2 had a max age of 3 seconds but as this thread slept for 4 seconds, it got cleared from the cache. For movie 3 we had set max age again to default value, hence it was still there in the cache.
Similarly, we can apply other attributes like idle time etc at each element level

 

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 *