Java JCache


In this post, I am going to explain about JCache.

What is JCache

  • JCache is given by Java (JSR-107)
  • It is Java Cache library specification, implemented by so many third-party vendors.
  • A common API to create, access, update, delete data from Cache.
  • But it's not part of JavaSE, we need to download the jar.

What are the implementations of JCache

  1. JCache Reference Implementation
  2. Hazelcast
  3. Oracle Coherence
  4. Terracotta Ehcache
  5. Infinispan

Why Cache

  • To increase the performance of the application.
  • To decrease the hits of database or rest calls so many times.

When to use Cache

  • When applications use the same data multiple times.
  • When time or resource of making rest calls or database hits are costly compared to get it from the cache

How Cache will work

  • Caches are stored in RAM to process with high speed
  • Cache efficiency = No. Of Cache hits / No. of total hits

How to download the JCache

<dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>1.0.0</version>
</dependency>

Link to download https://mvnrepository.com/artifact/javax.cache/cache-api/1.0.0

Create JCache Example

	public static void main(String[] args) {
		CacheFactory.ensureCluster();
		CachingProvider cachingProvider = Caching.getCachingProvider();
		CacheManager cacheManager = cachingProvider.getCacheManager();

		PassThroughCacheConfiguration<String, Integer> config = new PassThroughCacheConfiguration();
		config.setTypes(String.class, Integer.class);

		cacheManager.createCache("sampleCache", config);
		Cache<String, Integer> cache = cacheManager.getCache("sampleCache", String.class, Integer.class);

		cache.put("Id", 100);

		System.out.println("Value in cache is " + cache.get("Id"));

	}