Cookie Consent by Free Privacy Policy Generator JCache Provider for NCache

JCache Provider for NCache

NCache acts as a distributed JCache Provider, allowing Java applications to utilize JSR 107 compliant caching to eliminate database bottlenecks and scale horizontally. JCache is a Java based API used for in memory caching of Java objects. This also includes creation of objects, invalidation, spooling, shared access and consistency across Java Virtual Machines (JVMs).

NCache is a very powerful and versatile distributed caching solution that comes with a vast set of features and tools. NCache provides a high-performance implementation of the JSR 107 specification, ensuring full compatibility for Java applications requiring distributed caching with sub-millisecond latency. By leveraging this implementation, you can integrate NCache's enterprise-grade features into your JCache-compliant environment without architectural friction.

How do you initialize a JCache instance in NCache?

The creation of a JCache instance is required in order for you to perform any operations on the cache. In Java, the getCache () method is considered to be one of the most convenient methods of getting JCache instance. The following code example demonstrates how you can initialize a cache using this method.

/*Create an instance of JCache's caching provider to get JCacheManager's instance */
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();

/*Get a cache from manager via its string name.*/
javax.cache.Cache jCache = manager.getCache("myreplicatedcache");

What are the basic JCache operations supported by NCache?

Once the cache has been initialized successfully and you have acquired a cache handle, you can perform many operations on the cache like adding, fetching, updating, and deleting data from the cache.

The following code example demonstrates how you can use the cache instance (which you created in the code example above) to perform basic operations on the cache.

/*Adding data to the cache*/
Product product = fetchProductFromDB();
String key = "Product:" + product.getProductID();       
jCache.put(key, product);

/*Update data in the cache*/
product.setUnitsInStock(newValue); // updated units
jCache.replace(key, product);
	
/*Get data from the cache*/
Object item = jCache.get(key);
	
/*Remove data from the cache*/
Boolean result = jCache.remove(key);

How does JCache manage data expiration in NCache?

Another feature of JCache is Data Expiration where cache data is expired on the basis of time. JCache supports two main types of expirations namely Absolute Expiration and Sliding Expiration. In Absolute expiration, data within the cache is expired after a fixed time interval. In Sliding expiration, data within the cache is expired after a time interval but, this time interval is reset every time this data is accessed.

Items can be added and updated in the cache with Absolute and Sliding expirations defined. In the following code example data is added into the cache with Absolute expiration defined.

CachingProvider cachingProvider = Caching.getCachingProvider();
CacheManager manager = cachingProvider.getCacheManager();
    Customer customer = new Customer();
    customer.setAge(22);
    String key = "Customer:" + customer.getCustomerID();

    //configure the expiration duration
    CompleteConfiguration<Object, Object> cacheConfig = new MutableConfiguration().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));

    //create cache with customized configuration settings
    javax.cache.Cache jCache = manager.createCache("mypartitionedcache", cacheConfig);

    //add item to cache which will expire after 1 minute
    jCache.put(key, customer);

Monitoring Cache Events with JCache Listeners

Cache Level Notifications are general events that are triggered when certain registered events occur. In order to get event(s) notifications from JCache, you need to implement the relevant event related interfaces.

In the example below, it is assumed that you have implemented the event-filter factory.

// class that implements the event-listener factory
public class MyCacheEntryListener<K, V>
   implements CacheEntryCreatedListener<K, V>, Serializable
   {...
           for (CacheEntryEvent<? extends K,? extends V> event: events)
            {
            System.out.println("Received a " + event);
            }
      ...
    }
    ...
//configuring
MyCacheEntryListener<String,String> m_listener = new MyCacheEntryListener<String,String>();

MutableConfiguration<String, String> config = new MutableConfiguration<String, String>();

config.setTypes(String.class, String.class).addCacheEntryListenerConfiguration(
                    new MutableCacheEntryListenerConfiguration<String, String>
                            (FactoryBuilder.factoryOf(m_listener),FactoryBuilder.factoryOf(
                                    new MyCacheEntryEventFilter<String, String>()),true,true));

Cache<String, String> jCache = cacheManager.createCache("myreplicatedcache", config);

Using NCache API

The API provided by NCache gives you more robust features and functions as compared to the API provided by JCache. Some of the features which NCache provides but JCache does not are as follows:

Some of the features which NCache provides but JCache does not are as follows:

Feature Standard JCache (JSR 107) NCache JCache Provider
Search Key-based only SQL & LINQ Querying
Data Tags Not supported Supported via unwrap
Persistence Basic Read-Through/Write-Through
Scaling Limited by JVM Linearly Scalable Cluster

In order to use all of these features provided by the NCache API you need to have an instance of its cache.

The following code example demonstrates how you can use a JCache API to get a cache instance of NCache by using the unwrap method. This Instance is then used to add data into the cache with tags (feature of NCache) enabled. These tags can be used instead of keys to retrieve data from the cache later on.

... 
com.alachisoft.ncache.client.Cache cache = null;
cache = (com.alachisoft.ncache.client.Cache) jCache.unwrap(com.alachisoft.ncache.client.Cache.class);
Customer customer = fetchCustomer();
String customerKey = “Customer” + customer.getCustomerID();

// Specify Tags
List<Tag> tags = List.of(new Tag("East Coast Customers"));
CacheItem cacheItem = new CacheItem(customer);
cacheItem.setTags(tags);
cache.add(customerKey, cacheItem);

What to Do Next?

Frequently Asked Questions (FAQ)

The NCache JCache Provider is a 100% compliant implementation of the JSR 107 (JCache) specification. It allows Java developers to use a standardized caching API while benefiting from NCache’s distributed architecture, ensuring high availability and linear scalability for Java applications.

Migration is straightforward because NCache adheres strictly to the JSR 107 standard. You simply need to include the NCache JCache jar files in your project and configure the CachingProvider to point to your NCache cluster. No proprietary code changes are required for basic caching operations.

Yes. NCache fully implements JSR 107 ExpiryPolicy (including Absolute and Sliding expiration) and CacheEntryListener interfaces. This ensures that your cache eviction logic and event-driven workflows remain consistent when moving from a local cache to an NCache distributed cluster.

Yes. By using the javax.cache.Cache.unwrap method, you can access the underlying NCache API. This enables advanced features not found in the standard JSR 107 specification, such as SQL-like querying, item tagging, and database synchronization.

Absolutely. NCache provides dedicated providers for Spring Cache and Hibernate Second Level Cache (L2) that leverage the JCache standard. This allows for seamless integration into enterprise Java frameworks to reduce database load and improve response times.

© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.