Skip to content

lekhana3003/SimplCache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 

Repository files navigation

SimplCache - An Easy Java Cache Library

Maven Central License
SimplCache library can be used to implement cache instantly.
The library takes implementations of two databases,

  • Cache Database
  • Persistent Database

After which it provides all the features of cache seamlessly.

Table of Contents

1. Features

The features provided by the library are,

  • Easy Implementation
    To implement the cache the user has to implement only two interfaces (i.e CacheDB and PersistentDB). These databases can be of any type.(Relational or Non-Relational database) and rest is taken care by the SimplCache.
  • Least Recently Used (LRU) Eviction
    Least recently used cache object is evicted when cache reaches maximum limit.
  • Timed Eviction
    Objects are removed from the cache after the given interval time.
  • Write Through
    The data is simultaneously updated to cache and persistent database.
  • Write Back
    The data is updated only in the cache and updated into the persistent database in later time.
  • Automated Write Back
    The data in the cache is regularly updated in the persistent database at the interval given by the user.
  • Cache Size
    The cache size can be given either as count of the objects to be stored in cache or the actual memory occupied by the objects in the cache (i.e KiloBytes).
  • Save State
    Save the state of the cache at any point in time by calling a simple method and rebuild the same cache at any point by calling simple method.

2. Setup

Maven:

 <dependency>
    <groupId>com.github.lekhana3003</groupId>
    <artifactId>SimplCache</artifactId>
    <version>1.2.x</version>
  </dependency>

Gradle:

dependencies {
   implementation 'com.github.lekhana3003:SimplCache:1.2.x'
}
IMPORTANT To set the cache size in terms of object memory VM options have to be enabled while executing the main class of your project.
Otherwise, this can be skipped if object count option is used.
Refer:Cache Memory Types
  • Download the JAR
  • Execute java function by enabling VM options as: java -javaagent:"path to downloaded jar"
    Ex:java -javaagent:"../SimplCache.jar"
For Reference:
VM Options in Eclipse
VM Options in Intellij
Dynamically Enabling VM options

3. Usage

3.1 Getting Started

To implement cache using the library, it requires some methods to be implemented which are present in the interfaces CacheDB and PersistentDB. The SimplCache object is built using the SimplCache Builder. The Constructor of the builder takes two objects of CacheDB and PersistentDB.The model of the object that has to be stored in the cache has to be provided while implementing the interfaces.
Example:
The object to be stored in the cache is Car Model.
For CacheDB:

public class CacheDBImpl implements CacheDB<Car> {
...
}

For PersistentDB:

public class PersistentDBImpl implements PersistentDB<Car> {
...
}

To build the SimplCache Object:

CacheDBImpl cacheDB=new CacheDBImpl();
PersistentDBImpl persistentDB= new PersistentDBImpl();
SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB).build()

NOTE:

By default, the Eviction policy is set to LRU and Cache type is set as Write-through.


3.2 Setting Cache Properties

3.2.1 Eviction Policy

setEvictionPolicy is used to set the eviction policy which accepts an enum of EVICTION_TYPES. There are two types of eviction policies provided currently,

  • LRU Eviction
    Whenever a new object is put into the cache the least recently used object is evicted from cache after writing the object into cache.
    SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
            .setEvictionPolicy(SimplCache.EVICTION_TYPES.LRU_EVICTION)
            .build();
  • Timed Eviction
    Time eviction is used when the cache objects have to remain in cache only for certain amount of time. By setting this property, a new single thread runs parallel to the main thread which is responsible for removing the object from the cache after the time out. Before evicting the object from the cache the current data is automatically written into the persistent database.

    setTimeEvictionInterval() method is used to set the interval after which the object in cache expires.It accepts time integer and the unit of time as TimeUnit Object.If time eviction interval is not set, default value of 10 minutes is set.
    SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
            .setEvictionPolicy(SimplCache.EVICTION_TYPES.TIME_EVICTION)
            .setTimeEvictionInterval(30,TimeUnit.SECONDS)
            .build();

NOTE:

The implemeneted time eviction follows a combination of LRU and Time eviction i.e. if the cache is full at any point and no object in cache has timed out then the least recently object is removed from the cache to add the new object.


3.2.2 Cache Type properties

setCacheType() method is used to set the cache type of the cache. It accepts an enum CACHE_TYPES.There are two types of cache available currently,

  • Write-Through
    The object is immediately written into persistent database after writing into cache database.
    SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
            .setCacheType(SimplCache.CACHE_TYPES.WRITE_THROUGH)
            .build();
  • Write-Back
    The object in cache is not immediately updated in cache but later in time. There are two types of write-back options available,
    • NO_AUTO
      The write back into the persistent database from cache database happens only when writeBack() method is called or when the object is evicted from cache. The write back does not happen automatically.
        SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
                          .setCacheType(SimplCache.CACHE_TYPES.WRITE_BACK)
                          .build();
    • AUTO
      In this variation write back occurs at regular interval which is given by the user. A seperate new single thread is created and this thread is responsible for writing back only those objects that have been modified. setWriteBackInterval() takes two parameters time integer and the unit of time as TimeUnit Object.
      SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
                        .setCacheType(SimplCache.CACHE_TYPES.WRITE_BACK)
                        .setWriteBackInterval(30,TimeUnit.SECONDS)
                        .build();

3.2.3 Cache Memory Types

The library provides two types of cache size options, i.e. depending on Objects size and Objects count.
To set the memory properties, setCacheMemoryProperties() is used. It takes two parameters,

  • MEMORY_TYPES enum which has OBJECTS_SIZE and OBJECTS_COUNT
  • Maximum size of the cache, the size of cache is in KiloBytes(KB) if memory type is given as OBJECTS_SIZE and count if the OBJECTS_COUNT is given as memory type.

The default value of MEMORY_TYPES is OBJECT_COUNT and the default size is 50.

SimplCache<Car> simplCache=new SimplCache.SimplCacheBuilder<Car>(cacheDB,persistentDB)
        .setCacheMemoryProperties(SimplCache.MEMORY_TYPES.OBJECTS_COUNT,10)
        .build();

3.3 Put Method

This is an important method which is used to put object inside the cache. If the the cache is full, this method is responsible for performing the eviction according to the eviction policy selected by the user. This method takes two parameters Key(String) and the Object.

Car car=new Car("2","Car Model","2020");
simplCache.put("2",car);

Another variation of this method, If the user requires the object only to be added into cache but not into persistent database i.e if the user wants the put method not to perform write-through or write-back the user can use this variation.

Car car=new Car("key","Car Model","2020");
simplCache.put("key",car, SimplCache.POLICY_CONTROL.WITHOUT_POLICY);

3.4 Get Method

This method gets the object from the cache. If the object is not present in the cache, this method fetches the object from persistent database and also adds this object into the cache. This method requires the key of the object.

Car car = simplCache.get("key");

3.5 Write-Back Method

This method is responsible for writing the cache objects into persistent database. This method writes only the object which have been modified. This can be used whenever user wants to manually write the modified objects into the persistent database.

simplCache.writeBack();

3.6 Flush Method

This method is used to clear all the objects in cache. It accepts a single parameter of WRITEBACKPARAMETER enum. This parameter given by the user decides if the modified objects should be written into the persistent database before flushing.

  • WITH_WRITE_BACK
    simplCache.flush(SimplCache.WRITEBACKPARAMETER.WITH_WRITE_BACK);
  • WITHOUT_WRITE_BACK
    simplCache.flush(SimplCache.WRITEBACKPARAMETER.WITHOUT_WRITE_BACK);

3.7 Close Method

This method is used to close all the resources that have been opened by the SimplCache object. The database connections of CacheDB and PersistentDB can be closed using this function. The user has option to override if the user chooses to.
The close method takes a single parameter. This parameter given by the user decides if the modified objects should be written into the persistent database before closing.

  • WITH_WRITE_BACK
    simplCache.close(SimplCache.WRITEBACKPARAMETER.WITH_WRITE_BACK);
  • WITHOUT_WRITE_BACK
    simplCache.close(SimplCache.WRITEBACKPARAMETER.WITHOUT_WRITE_BACK);

3.8 Save State

Saving:

This method is used to save the state of cache at any given time. This method returns a string which is encrypted with default encryption algorithm. If the user wants to implement any other encryption mechanism, the user is required to pass an object of class which has implemented SimplCacheEncryptor. The cache objects are written back into persistent database before saving the state, This method returns only the keys of cache object and also stores the properties which are set for the cache in the SimplCache object. It does not store the entire object which is stored in the cache. The two variations as follows,

  • With default encryptor,
    String state = simplCache.saveState();
  • With implemenation of SimplCacheEncryptor
    Implemenation class
    public class SimplCacheEncryptorImpl implements SimplCacheEncryptor {
        ...
    }
    SimplCacheEncryptorImpl simplCacheEncryptorImpl=new SimplCacheEncryptorImpl();
    String state = simplCache.saveState(simplCacheEncryptorImpl);
Building from save state:

This method is used to build back the cache from the string which is returned by the saveState() method. This method restores cache objects from persistent database. This method takes cacheDB and persistenseDB implemented objects again along with optional SimplCacheEncryptor object.

  • With default encryptor,
    SimplCache<Car> simplCache1=SimplCache.buildFromSaveState(state,cacheDB,persistentDB);
  • With implemenation of SimplCacheEncryptor
    SimplCache<Car> simplCache1=SimplCache.buildFromSaveState(state,cacheDB,persistentDB,simplCacheEncryptorImpl);

NOTE:

The default encryptor does not guarantee any security.


4. Example

Spring Boot implemenation of SimplCache Library

5. License

   Copyright 2020 Lekhana Ganji

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

6. Author