Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Using Java Caching System for Distributed Apps

Caching technique has been adopted and widely accepted in order to have a high performance application in place. In this article we will talk about the Java Caching System or JCS, its features, techniques and components.

Caching technique has been adopted and widely accepted in order to have a high performance application in place. In this article I will talk about the Java Caching System or JCS, its features, techniques and components, which can help us to have a robust application in place.

Java Caching System, or JCS, is a distributed caching system which is designed and developed using Java. The main goal of JCS is to speed up the applications. This is done by providing a mechanism to manage the cached data of different dynamic natures. Similar to any other caching system, JCS is very much helpful for high read, low put applications. If we can have an effective cached system, latency time comes down sharply and also the bottlenecks go away from applications. JCS works on JDK 1.4 or higher version of Java.

Features of JCS

JCScomes with an array of features. The important ones are listed below -

  • Memory management - JCS has in inbuilt capacity to manage the memory at runtime.
  • Disk overflow and defragmentation - JCS defrags the disks automatically in case the disk is full.
  • Thread pool controls - JCS controls the thread pools very efficiently.
  • Element grouping - JCS has a feature due to which elements having common properties are grouped together so that they can be referred efficiently as and when required.
  • Quick nesting categorical removal - JCS can provide faster nesting among objects and at the same time it can also categorically remove the less used or unused objects.
  • Data expiration - Using JCS, any developer can rely on the data expiration feature it provides.
  • Extensible framework - The framework is extensible and very easy to implement.
  • Fully configurable runtime parameters - JCS comes with self-explanatory runtime parameters which can be easily configured at runtime.
  • Region data separation and configuration - JCS has the ability to segregate the data based on region which is also configurable.
  • Fine grained element configuration options.
  • Remote synchronization.
  • Remote store recovery.
  • Lateral distribution of elements via HTTP, TCP, or UDP - Using JCS, data can be transmitted and distributed via any of the standard protocols e.g. HTTP or TCP or UDP.
  • Element event handling - JCS is capable of handling object wise events.
  • Remote server chaining (or clustering) and failover - JCS supports clustering and can easily handle the failover situations.
  • Custom event logging hooks.
  • Custom event queue injection.
  • Custom object serializer injection - JCS supports the usage of serialized objects and also their injection at any point of time in the course of application running.
  • Key pattern matching retrieval.
  • Network efficient multi-key retrieval.

JCS - a composite cache

JCS is based upon the concept of the Composite Cache. Composite Cache is nothing but a pluggable controller of the entire cache region. There are four types of caches which can be plugged into the Composite Cache. These are

  • Memory,
  • Disk,
  • Lateral, and
  • Remote.

The Composite Cache organizes the access to the different caches which are configured to be used in a region. The JCS library provides ready to use implementations of each of the above four category of caches. In addition to the above core four, JCS also provides additional plugins of each type.

LRU Memory Cache

The LRU Memory Cache is the most fast and highly configurable memory cache. LRU stands for 'Least Recently Used'. It uses the 'Least Recently Used, based algorithm to maintain the number of items which can be stored in memory. The LRU Memory Cache has an inbuilt LRU Map implementation. This map is significantly faster than the commons LRUMap implementation and the LinkedHashMap which comes with JDK1.4 and above. This ensures that JCS is faster than its competitors.

Indexed Disk Cache

Indexed Disk Cache is also a fast, reliable, and configurable swap used for cached data. This type of cache uses the fastest algorithm for disk swapping. The Cached elements are copied onto the disk using queue-based mechanism which runs continuously. The length of the item is kept in the initial bytes of the entry. The offset is maintained in the memory and can be referenced using a key. When items move out of the disk cache, the location and size are recorded and reused whenever required. Every parameter aspect of the disk cache can be configured easily, and also a thread pool is used so that the number of queue worker threads across the system can be monitored and reduced if required.

JDBC Disk Cache

JDBC Disk Cache is a fast, reliable, and highly configurable disk cache. It has the ability to store both the keys and the corresponding elements in a database which is JDBC based. The JDBC disk cache stores the elements in the database in the form of binary large objects or BLOBs. The database table is swept from time to time in order to remove the elements which are expired. Multiple instances can be configured in order to use a common connection pool. A thread pool can be used so that the number of queue worker threads across the system can be configured. The MySQL version of the JDBC Disk Cache can optimize and repair tables.

TCP Lateral Cache

The TCP Lateral Cache comes with an easy mechanism to distribute cached data on multiple servers. It comes with a UDP discovery mechanism, so we can easily add nodes without having to reconfigure the entire unit. The TCP Lateral Cache starts working when the connections are established with socket server running on other nodes. Each node maintains a connection to every other node. Only one server is required here for any number of regions. The client is smart enough to re-establish the connections if it is lost with another server. The TCP Lateral cache is highly configurable . We have the options here -
  • only to send data
  • not look for data on other servers
  • send removes instead of puts
  • filter out removes based on hash codes.

RMI Remote Cache

JCS also provides a Remote Cache Server which is RMI based. Rather than having each and every node connected to other node, we can use the remote cache server as the point of connection. Each node is connected to the remote server, which usually broadcasts events to the other nodes. In order to maintain the consistency across the cluster without taking the overhead of serialization, you can send invalidation messages to the other local nodes rather than sending an object over the network. The remote cache server stores a serialized version of your objects; hence it is not required to be deployed with our developed class libraries. All the remote servers can be chained along with a list of failover servers can be configured on the client.

Myths about JCS

There are certain myths about JCS which we should be aware of while working with it. Some of them are listed below -

  • JCS is not a tag library or a web based application. Rather it is a generic caching system which can be used in generic web applications, web services or stand-alone applications.
  • JCS is not a transactional distributed system. It is a cache and not a database.
  • JCS does not use AOP. It does not manipulate the user defined objects.

Working with JCS

Now, let us talk about a simple application in which we will see how to setup JCS and then work with JCS. Setting up JCS is very simple. Just download the following jar libraries and add their path to the environment variable - 'CLASSPATH' -

  • jcs-1.3.jar
  • commons-logging.jar
  • commons-lang-2.4.jar
  • concurrent.jar

Let us have an example where we can see the implementation of JCS. We are talking about a simple implementation of a Student entity and its cache manager implementation. The classes are listed below –

Listing 1: This is student Class

package com.home.jcs;
public class Student implements Serializable{
     * The Serial ID of this object
    private static final long serialVersionUID = -1178562509615004752L;
    private int studentId;
    private String fName;
    private String mName;
    private String lName;
    private String stream;
    public Student () {
    public Student( int studentId, String fName, String mName, String lName, String stream ) {
        this.studentId = studentId;
        this.fName = fName;
        this.mName = mName;
        this.lName = lName; = stream;
     * @return the studentId
    public int getStudentId () {
        return studentId;
     * @param studentId the studentId to set
    public void setStudentId( int studentId ) {
        this.studentId = studentId;
     * @return the fName
    public String getfName () {
        return fName;
     * @param fName the fName to set
    public void setfName( String fName ) {
        this.fName = fName;
     * @return the mName
    public String getmName () {
        return mName;
     * @param mName the mName to set
    public void setmName( String mName ) {
        this.mName = mName;
     * @return the lName
    public String getlName () {
        return lName;
     * @param lName the lName to set
    public void setlName( String lName ) {
        this.lName = lName;
     * @return the stream
    public String getStream () {
        return stream;
     * @param stream the stream to set
    public void setStream( String stream ) { = stream;

Listing 2: This is student Cache Manager Class

package com.home.jcs;
import org.apache.jcs.JCS;
import org.apache.jcs.access.exception.CacheException;
public class StudentCacheManager {
    private JCS cache;
    public StudentCacheManager () {
        try {
            // Load the cache
            cache = JCS.getInstance( "studentCache" );
            // Initialize the cache, Here data can be loaded during initialization
            cache.put( "123", new Student( 123, "John", "Swizher", "Weige", "Civil") );
            cache.put( "143", new Student( 143, "Theoder", "", "Sattler", "Computer Science" ) );
            cache.put( "153", new Student( 153, "Martin", "Sam", "Suckhorozka", "Electrical" ) );
            cache.put( "163", new Student( 163, "Russel", "", "Latour", "Mechanical" ) );
        } catch ( CacheException e ) {
            e.printStackTrace ();
    public void addStudent( Student student ) {
        try {
            cache.put( student.getStudentId(), student );
        } catch ( CacheException e ) {
            e.printStackTrace ();
    public Student getStudent( int studentId ) {
        return (Student) cache.get( studentId );
    public void removeStudent( int studentId ) {
        try {
            cache.remove( studentId );
        } catch ( CacheException e ) {
    public static void main( String[] args ) {
        // Create the student manager
        StudentCacheManager studentManager = new StudentCacheManager ();
        // Add students to the student manager
         * studentManager.addStudent( new Student(123, "John", "Swizher", "Weige", "Civil" ) );
         * studentManager.addStudent( new Student(1243, "John", "Swizher", "Weige", "Civil" ) );
         * studentManager.addStudent( new Student(1234, "John", "Swizher", "Weige", "Civil" ) );
        // Get student
        Student stud = studentManager.getStudent ( 123 );
        System.out.println("Student details retrieved from cache: " + stud.getfName () + "-" + stud.getmName () + "-" + stud.getlName () );
        // Remove Student
        studentManager.removeStudent (123) ;
        // After removal of Student
        System.out.println( "Student details after removal from cache: " + studentManager.getStudent( 123 ) );

Listing 3: This is configuration file

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 = false 
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 
jcs.region.studentCache = DC 
jcs.region.studentCache.cacheattributes = org.apache.jcs.engine.CompositeCacheAttributes 
jcs.region.studentCache.cacheattributes.MaxObjects = 1000 
jcs.region.studentCache.cacheattributes.MemoryCacheName = org.apache.jcs.engine.memory.lru.LRUMemoryCache 
jcs.region.studentCache.cacheattributes.UseMemoryShrinker = false 
jcs.region.studentCache.cacheattributes.MaxMemoryIdleTimeSeconds = 3600 
jcs.region.studentCache.cacheattributes.ShrinkerIntervalSeconds = 60 
jcs.region.studentCache.cacheattributes.MaxSpoolPerRun = 500 
jcs.region.studentCache.elementattributes = org.apache.jcs.engine.ElementAttributes 
jcs.region.studentCache.elementattributes.IsEternal = false 
jcs.auxiliary.DC = org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory 
jcs.auxiliary.DC.attributes = org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes 
jcs.auxiliary.DC.attributes.DiskPath = c:/temp 
jcs.auxiliary.DC.attributes.MaxPurgatorySize = 10000000 
jcs.auxiliary.DC.attributes.MaxKeySize = 1000000 
jcs.auxiliary.DC.attributes.MaxRecycleBinSize = 5000 
jcs.auxiliary.DC.attributes.OptimizeAtRemoveCount = 300000 
jcs.auxiliary.DC.attributes.ShutdownSpoolTimeLimit = 60

In the example shown above, Student class is the entity which is being stored in the cache. The StudentCacheManager is the main class which uses the JCS libraries. This class uses a cache region - 'studentCache'. This cache is used to store data into memory and also to retrieve data from memory. The data is stored using a key - value pair format, so that it can be easily retrieved.

The configuration file - cache.ccf holds all the configurable parameters along with their values. Here the first section is the default cache region which defines the default values. If no custom region is defined, then the default parameters will be used. The second section defines the custom cache region which is the 'studentCache' in our case. This defines the custom parameter values. The third section is the AUXILIARY CACHE region which describes the disk cache and other related parameters.

JCS in enterprise applications

The Multi-tier architectures come with an advantage that they can help make complex enterprise applications manageable and scalable. As the number of servers and the layers go up, the communication between them also goes up. This can well degrade the overall application performance. Most of the web applications, data is shown retrieving from a database. Any operation on this database is quite expensive and also time consuming.

The current web applications are data centric and faster response time is the basic criteria for their success. If in the web application it is required to frequently access the database for each and every request then it is bound to have a low performance. In a standard enterprise application we normally cache the objects by using object caching mechanism. This allows the applications to share objects across multiple requests and users, this also coordinates the objects’ life cycle across different processes. We can also use the concept of web caching. Web cache sits between multiple Web servers. These web servers are also known as the originating servers for the clients, one or many. These servers keep a track of the requests that are coming. They also save copies of the responses — e.g. HTML pages, images and files for itself. If there is another request for the same URL, it can use the response which it has saved, rather than asking the origin server for it again.

Why Caching is required in enterprise applications

Uses of caching mechanism at different strategic points across a multi-tier application, helps us reduce the number of back-and-forth communication. Though, the cache repositories requires memory and CPU resources, it is always better to use the caching techniques as these can help us to gain the overall performance of an applications by reducing the number of expensive server trips and db operations. However, it is quite a challenging task to ensure that cache retains fresh contents and the stale data is discarded. Also keeping multiple caches in sync in a clustered environment is even more complicated. In case of object caching, we can eliminate the need of creating the objects and loading the data by storing frequently accessed or expensive-to-create objects in the cache memory. It helps us to get rid of expensive reacquisition of objects by not releasing the objects immediately after their use. Instead, these objects are stored in memory and reused for any subsequent client requests.

Web cache is used to reduce the latency. It takes much lesser time to get the representation and display it. It helps reduce the load on the website servers and also reduces the bandwidth needs and cost. It provides benefits to all - the user, the service provider and the website owner.

Features of JCS frameworks

Several Open Source Caching Frameworks for Java are available e.g. -

  • JBoss Cache,
  • OSCache,
  • Java Caching System and
  • EhCache.

Direct cache methods e.g. Java Hash map, Hash table and JNDI have certain drawbacks which are overcome by these frameworks.

JBoss Cache is a product, which is designed to cache frequently used Java objects or POJOs to help improve the performance of any e-business applications. This is done by eliminating unwanted database access. JBoss Cache helps in reducing the network traffic and thus increases the scalability of applications. JBoss Cache supports all the transactional features and at the same time it also provides a highly configurable set of options that helps to deal with concurrent data access in an efficient manner possible.

OSCache is a widely used, high performance J2EE based caching framework. On top of its servlet-specific features, OSCache can also be used as a generic caching solution for any Java application. Some of its features are listed under:

  • Caching of Arbitrary Objects – Using OSCache, we are not restricted to cache only parts of JSP pages or HTTP requests. Any Java object can be cached.
  • Comprehensive API – The OSCache API provides full programmatic control on all of the OSCache features.
  • Persistent Caching – The cache can be disk based which is optional. Hence, it allows the data which are expensive in terms of creation to remain cached even when the application restarts.
  • Clustering – Support for clustering of cached data can be easily enabled with a single configuration parameter. No code change is required here.
  • Expiry of Cache Entries – We have a bigger control on how the cached objects expire. This includes pluggable refresh policies if the default functionality does not meet your requirements.

EhCache is a pure Java based in-process cache having the following features:

  • It is Fast
  • It is Simple
  • It Acts as a pluggable cache for Hibernate 2.1.
  • It has Small foot print, minimum dependencies, well documented and is production tested.

Comparison of different java caching frameworks

JBOSS cache: JBOSS Cache supports the following caching techniques -

  • LRU
  • LFU
  • MRU
  • Expiration
  • Element Size and
  • FIFO.

JBoss cache does not support the presentation layer which means it has nothing for JSP and HTTP Responses. JBoss cache provides a very simple and straightforward API using which the data can easily be stored in the cache. It caches the objects in the memory which offers an efficient thread safe retrieval mechanism. In JBoss cache, while the garbage collector starts executing in case the memory runs low it easily copies the cached content to the disk, thus ensuring that the memory is not lost. It supports distributed cache technique. It can be either local or replicated cache. When a change is made to an object which is in the cache and that the change is done in the context of the transaction, the change replication is deferred until the transaction is completed successfully. When the transaction committed, the changes are replicated. On a roll back situation, these changes are discarded. JBoss cache supports object sharing within the same JVM. When used in a clustered environment, this is an effective way to build high available, fault tolerant and load balanced application. It is scalable but is not much in comparison to others.

OSCache: OSCache supports LRU and FIFO and many other custom replacement algorithms. It provides mechanism to caching the presentation layer. This includes JSTL and set f classes which can perform JSP level caching and servlet responses. It has the ability to control the cache flushing. OSCache has to ability to partial cache of JSP pages, arbitrary java objects and even entire servlet response. It has an in memory and disk cache. It supports distributed caching. It also supports sharing of objects within the same JVM. While using both disk and memory caching it is possible to restrict the cache size in order to avoid overusing of memory. When the cached objects are removed from the memory, they still occupy space on the disk. This provides the fault tolerance feature in case the server crashes. It is highly scalable. OSCache is easy to use and also easy for maintenance. This is s fully event driven. In terms of performance, it is considerably slower than JBoss cache if when we compare with the PUT and Get requests.

EhCache: EhCache supports LRU, LFU and FIFO caching techniques. EhCache has the ability to store up to 100GB of data on to the disk and access them in a faster manner. It provides SimplePageCachingFilter which is used to caching static pages. It also compresses the HTTPResponse to the browser using the most efficient compression algorithm. The browser then de-compresses the response and puts it to the client. In case of dynamic pages e.g JSP and JSF, EhCache provides SimplePageFragmentCachingFilter to cache the static part. It does not provide any JSTL like OSCache for page fragment cache and page fragment cache is view agnostic. It is flexible, extensible, and high performing distributed caching. The default implementation support cache discovery via multicast or manual configuration. Updates are delivered either asynchronously or synchronously via custom RMI connections.


Through this article, we have tried to cover as many aspects of JCS and its features and components as possible. Let us conclude our discussion in the form of following bullets -

  • Java Caching System or JCS is a distributed caching system which is designed and developed using Java.
  • The main goal of JCS is to speed up the applications.
  • JCS comes with an array of features which are listed above.
  • There are certain myths about JCS which we should be careful of.
  • JCS helps enterprise applications to scale up and have a better performance.

We hope this document gave you a better idea about JCS. We hope you enjoyed reading this article.

Website: Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login