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

What is Java Caching System (JCS)?

Java Caching System is a very important part of the Java Specification for memory-cache purposes. In this article we will see how to use it with some examples.

Java is a programming language and a software platform that is very widely used for the development of numerous applications. It finds usage in a large number of applications, right from embedded systems to cell phones, servers and even supercomputers.

Now, many of the applications that are developed using Java employ the usage of a distributed in-memory cache for data. They are placed either before, or even to replace persistent storage for certain number of tasks. This is exactly the use of Java Caching System.

What is a cache?

Many people are familiar with what a cache, in computer parlance means, but in case you don’t, here’s a basic idea.

A cache primarily happens to be a certain area in the local memory that retains a copy of the most frequently accessed data. The sole reason for doing so is because without it, the data can be incredibly costly in terms of computation, thereby slowing down the overall process. Some simple examples to that can be the result of a specific database query, a report, etc.

If you want to know more about Caching strategies in software development world, please refer some of our other articles:

What is JCS?

Java Caching System is a form of distributed caching method that has been written using Java.

What is the use of employing Java Caching System?

Generally, the primary use of Java Caching System, just like any other caching method, is to speed up applications. It does so by supplying a way to manage cached data of different types of dynamic components. Also, just like other caching systems, the use of JCS is very helpful in the case of applications that are low put, but high read. By using JCS in the proper manner, one can obtain a sharp reduction in latency times and also the removal of bottlenecks from a database.

Besides its primary function, JCS also allows for some more features such as –

  • Management of memory
  • Disk defragmentation
  • Grouping of elements
  • Expiration of data
  • Extensible framework
  • Event handling of elements
  • Remote synchronization and store recovery
  • Using HTTP, TCP and UDP to laterally distribute elements

A number of other features haven’t been included here.

Implementation of Java Caching System

Now that we have learnt what a Java Caching System is and have a fair idea of its usage and advantage, let us take a look into how you can implement one. The code snippet provided below is just a simple example that will enable you to understand and implement an in-memory cache using Java.

Listing 1:

package javacachingsystemtutorials;
import java.util.ArrayList;
import org.apache.commons.collections.MapIterator;
 * author JCS
public class JCSInMemoryCache<k, t> {
    private long TimetoLive;
    private LRUMap JCSCacheMap;
    protected class JCSCacheObject {
        public long last_accessed = System.currentTimeMillis();
        public t value;
        protected JCSCacheObject(t value) {
            this.value = value;
    public JCSInMemoryCache(long JCSTimetoLive, final long JCSTimerInterval, int maxitems) {
        this.TimetoLive = JCSTimetoLive * 1000;
        JCSCacheMap = new LRUMap(maxitems);
        if (TimetoLive > 0 && JCSTimerInterval > 0) {
            Thread th = new Thread(new Runnable() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(JCSTimerInterval * 1000);
                        } catch (InterruptedException ex) {
    public void put(k key, t value) {
        synchronized (JCSCacheMap) {
            JCSCacheMap.put(key, new JCSCacheObject(value));
    public t get(k key) {
        synchronized (JCSCacheMap) {
            JCSCacheObject c = (JCSCacheObject) JCSCacheMap.get(key);
            if (count == null)
                return null;
            else {
                count.lastAccessed = System.currentTimeMillis();
                return count.value;
    public void remove(k key) {
        synchronized (JCSCacheMap) {
    public int size() {
        synchronized (JCSCacheMap) {
            return JCSCacheMap.size();
    public void cleanup() {
        long now = System.currentTimeMillis();
        ArrayList<k> deleteKey = null;
        synchronized (JCSCacheMap) {
            MapIterator iter = JCSCacheMap.mapIterator();
            deleteKey = new ArrayList<k>((JCSCacheMap.size() / 2) + 1);
            k key = null;
            JCSCacheObject count = null;
            while (iter.hasNext()) {
                key = (k);
                count = (JCSCacheObject) iter.getValue();
                if (count != null && (now > (TimetoLive + count.last_accessed))) {
        for (k key : deleteKey) {
            synchronized (JCSCacheMap) {

The code snippet given above basically allows you to create an in-memory cache using JCS. The characteristics of the above program is as given –

  • Based on a time to live period, items are generally set to expire.
  • The cache will keep the most recently used items, as you keep on trying to add more than the maximum number of items that has been provided (the Apache collections consists of a LRUMap. This removes all the least used entries from the specified map).
  • We timestamp the last access made and then using a separate thread, remove items when the limit for time to live has been reached. This is the procedure followed for expiration of items.
  • We are also going to create and utilize a test class, that’ll help us determine the results of what we have just created.

Listing 2:

package javacachingsystemtutorials;
import javacachingsystemtutorials.JCSInMemoryCache;
 * @author JCS
public class JCSInMemoryCacheTest {
    public static void main(String[] args) throws InterruptedException {
        JCSInMemoryCacheTest JCSCache = new JCSInMemoryCacheTest();
        System.out.println("\n\n============Test_1: JCS_Test_Add_Remove_Objects ============");
        System.out.println("\n\n============Test_2: JCS_Test_Expired_Cache_Objects ============");
        System.out.println("\n\n============Test_3: JCS_Test_Objects_Cleanup_Time ============");
    private void JCSTestAddRemoveObjects() {
        // Testing with TimetoLive In Seconds = 300 seconds
        // TimerInterval In Seconds = 600 seconds
        // maxttems = 6
        JCSInMemoryCache<String, String> cache = new JCSInMemoryCache<String, String>(300, 600, 6);
        cache.put("Amazon", "Amazon");
        cache.put("PayPal", "PayPal");
        cache.put("Apple", "Apple");
        cache.put("Microsoft", "Microsoft");
        cache.put("Flipkart", "Flipkart");
        cache.put("Facebook", "Facebook");
        System.out.println("Six Cache Objects Added.. cache.size(): " + cache.size());
        System.out.println("One object removed.. cache.size(): " + cache.size());
        cache.put("Google", "Google");
        cache.put("Oracle", "Oracle");
        System.out.println("Two objects added, but reached maxitems.. cache.size(): " + cache.size());
    private void JCSTestExpiredCacheObjects() throws InterruptedException {
        // Testing with TimetoLive In Seconds = 2 seconds
        // TimerInterval In Seconds = 2 second
        // maxitems = 10
        JCSInMemoryCache<String, String> cache = new JCSInMemoryCache<String, String>(2, 2, 10);
        cache.put("Amazon", "Amazon");
        cache.put("PayPal", "PayPal");
        // Adding 5 seconds sleep.. Both above objects will be removed from
        // Cache because of TimetoLive In Seconds value
        System.out.println("Two objects are added but reached TimetoLive. cache.size(): " + cache.size());
    private void JCSTestObjectsCleanupTime() throws InterruptedException {
        int size = 600000;
        // Testing with TimetoLive In Seconds = 120 seconds
        // TimerInterval In Seconds = 120 seconds
        // maxitems = 600000
        JCSCache<String, String> cache = new JCSInMemoryCache<String, String>(120, 120, 600000);
        for (int i = 0; i < size; i++) {
            String value = Integer.toString(i);
            cache.put(value, value);
        long start = System.currentTimeMillis();
        double finish = (double) (System.currentTimeMillis() - start) / 1000.0;
        System.out.println("The Cleanup timings for " + size + " objects are " + finish + " s");

Using the code snippet given above, we can easily generate the output and test the code snippet given in the beginning, i.e. Listing 1. Also, we can determine the manner in which the actual implementation of Java Caching System functions.

What Java Caching System isn’t?

Now that we know what Java Caching System is and also how to go about implementing a simple one, let us also know what JCS isn’t.

  • JCS is basically a very general caching system that can be used for Java applications and web applications. However, it isn’t a tag library.
  • JCS happens to a cache and not a database. Therefore, it cannot be employed as a transactional distributive method.
  • JCS is non-invasive in nature and doesn’t manipulate objects in your code. Thus, it definitely isn’t Aspect Oriented Programming.
  • JCS isn’t a breakaway or fork of any sort, but rather a different project.


The above-given tutorial clearly defines all aspects of Java Caching System. Using that knowledge, we have also shown how you can actually create a JCS in memory. Further, we have also got code that helps us determine and test out the implementation of such a caching system.

As such, Java Caching System finds very good use in applications and helps in the speeding up of the working of such applications. Lower latency and removal of database bottlenecks are some of its primary uses. Besides, it also offers several other advantages that can largely benefit the implementation of several kinds of applications, whether they are Web-based or simply standalone types.

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