• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Java Third Party Integrations
  • JCache API
  • CRUD Operations
Show / Hide Table of Contents
  • Programmer's Guide
  • Setting Up Development Environment
    • .NET
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Java
      • Client API Prerequisites
      • Server-side API Prerequisites
    • Python
      • Client API Prerequisites
    • Node.js
      • Client API Prerequisites
  • Client Side API Programming
    • Error Handling
    • Troubleshooting
    • Cache Keys and Data
    • How to Connect to Cache
    • Basic Operations - An Overview
      • Add Data
      • Update/Insert Data
      • Retrieve Data
      • Remove Data
    • Groups
      • Overview
      • Add/Update Data with Groups
      • Retrieve Data with Groups
      • Remove Data with Group
      • Search Group Data Using SQL
      • Delete Group Data Using SQL
    • Tags
      • Overview
      • Add/Update Data with Tags
      • Retrieve Data with Tags
      • Remove Data with Tags
      • Search Tag Data Using SQL
      • Delete Tag Data Using SQL
    • Named Tags
      • Overview
      • Add/Update Data with Named Tags
      • Remove Data with Named Tags
      • Search Data with Named Tags Using SQL
      • Delete Data with Named Tags Using SQL
    • Expirations
      • Overview
      • Absolute Expiration
      • Sliding Expiration
    • Data Dependency
      • Key Dependency
      • Multi-Cache Dependency
    • Dependency on Database
      • SQL Server
      • Oracle
      • OleDB with Polling
      • CLR Procedures in SQL Server
    • Dependency on External Source
      • File Dependency
      • Custom Dependency
      • Aggregate Dependency
    • Locks
      • Types of Locking
      • Pessimistic Locking
      • Optimistic Locking
    • SQL Query
      • Overview
      • Define Indexes Programmatically
      • Query with ExecuteReader and ExecuteScalar
      • Delete Data with ExecuteNonQuery
      • SQL Reference
    • LINQ Query
      • Overview
      • LINQ Query for Objects
      • LINQ Reference
    • Data Structures
      • Overview
      • List
      • Queue
      • Set
      • Dictionary
      • Counter
      • Invalidation Attributes
      • Searchable Attributes
      • Query on Data Structures
      • Remove from Data Structure
    • Events
      • Cache Level Events
      • Item Level Events
      • Management Level Events
    • Pub/Sub Messaging
      • Overview
      • Topics
      • Publish Messages
      • Subscribe to a Topic
      • Pub/Sub Events
    • Continuous Query
      • Overview
      • Use Continuous Query
    • Stream Processing
      • Add/Update Stream Data
      • Retrieve Stream Data
    • JSON
      • Overview
      • Use JSON Objects
      • Query JSON Data
    • Security API
      • Login with Credentials
    • Management API
    • Clear Cache
    • Error Logging
    • Location Affinity
  • Server-side API Programming
    • Loader and Refresher
      • Overview
      • Implement Loader and Refresher
      • Components of Loader/Refresher
    • Data Source Providers
      • Read-through
        • Implement Read-through
        • Use Read-through
      • Write-through
        • Implement Write-through
        • Use Write-through
        • Use Write-behind
    • Custom Dependency
      • Implement Extensible Dependency
      • Implement Bulk Extensible Dependency
      • Implement Notify Extensible Dependency
    • Bridge Conflict Resolver
    • Entry Processor
      • Overview
      • Implement Entry Processor
    • MapReduce
      • Overview
      • Implement MapReduce
      • Use MapReduce
    • MapReduce Aggregator
      • Overview
      • Implement and Use Aggregator
    • Compact Serialization
  • Client Side Features
    • ASP.NET Core Caching
      • Session Storage
        • Session Provider
        • IDistributedCache
        • Sessions Usage
        • Multi-site Session Provider
        • Session Sharing with ASP.NET
      • SignalR
        • NCache Extension for SignalR Core
      • Response Caching
        • Configure and Use
        • Configure with IDistributedCache
      • Data Caching
        • NCache API
        • IDistributedCache API
      • Data Protection Provider
        • Configure
    • Java Web App Caching
      • Web Sessions
        • Overview
        • Configure App
          • Add Maven Dependencies
          • Deploy Application
        • Multi-site Sessions
    • Node.js App Caching
      • Web Sessions
    • ASP.NET Caching Benefits and Overview
      • ASP.NET Session State Provider Properties
      • Multi-region ASP.NET Session State Provider Configuration
      • Session Sharing between ASP.NET and ASP.NET Core
      • ASP.NET SignalR Backplane
        • NCache Extension for SignalR
      • ASP.NET View State Caching
        • View State Content Optimization Configuration
        • Group View State with Sessions
        • Limit View State Caching
        • Page Level Grouping
      • ASP.NET Output Cache
        • Output Caching Provider Overview
        • Output Cache with Custom Hooks
  • .NET Third Party Integrations
    • Entity Framework (EF) Core
      • Installation
      • Configure
      • EF Core Extension Methods
        • Extension Methods
        • Cache Handle
        • Caching Options
        • Query Deferred API
      • Logging in EF Core
    • Entity Framework EF 6
      • EF Second Level Cache
      • EF Caching Resync Provider
      • EF Caching Configuration File
    • NHibernate
      • Second Level Cache
      • Query Caching
      • Synchronize Database with Cache
    • Debug NCache Providers in Visual Studio
  • Java Third Party Integrations
    • Hibernate
      • Second Level Cache
      • Configure Cacheable Objects and Regions
      • Configure Application
      • Query Caching
    • Spring
      • Overview
      • Use NCache with Spring
        • Configure Generic Provider
        • Configure JCache Spring Caching Provider
        • Configure Caching Declaration
        • Configure Spring Sessions
    • JCache API
      • CRUD Operations
      • Expiration
      • Events
  • Third-Party Wrappers
    • AppFabric to NCache Migration
      • AppFabric API vs. NCache API
      • Configuration Differences Between AppFabric and NCache
      • Migrating from an AppFabric Application to NCache
    • Redis to NCache Migration
      • Redis to NCache Migration
    • Memcached Wrapper
      • Memcached Gateway Approach
      • Memcached Client Plugin for .NET

JCache: Initialize Cache

After successfully plugging NCache into your JCache application, a cache instance is required to perform cache operations. Java applications can also interact with NCache using the JCache API provider packaged as a part of NCache. The JCache API provider provides a convenient method to initialize the cache instance.

Prerequisites for JCache CRUD Operations

  • For using JCache with NCache Professional, replace the ncache-client with ncache-professional-client in your pom.xml.
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Include the following packages and their libraries in your application from the NCache install directory.
    • import javax.cache.CacheManager
    • import javax.cache.Caching;
    • import javax.cache.spi.CachingProvider;
  • Make sure that the data is serialized or registered with the NCache Serialization format.
  • Ensure that the cache is running.

Initialize Cache

To obtain a cache instance in Java, use the getCache method from the JCache CacheManager provided by NCache. You can get an instance of a previously configured cache by using its name (unique identifier) as an argument to the getCache method.

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

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

Obtaining NCache API's Cache Instance

NCache's API provides comparatively advanced caching features including Locking, Groups, Pub/Sub Messaging, Tags, and SQL-like querying capabilities, which can be crucial for complex, distributed, and high-load scenarios. To access all of NCache's features via JCache, you can utilize the unwrap method provided by NCache. This method allows you to obtain actual instance of NCache, which can then be used to access and utilize all of NCache's capabilities.

This example creates an instance of the JCache caching provider, which then retrieves the JCache Manager. From the manager, it unwraps the NCache instance and obtains a cache by its name.

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

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

// Unwrapping NCache's cache instance from JCache's cache instance.
com.alachisoft.ncache.client.Cache cache = (com.alachisoft.ncache.client.Cache) jCache.unwrap(com.alachisoft.ncache.client.Cache.class);

Initialize Multiple Caches in a Single Application

To initialize multiple caches in a single application, it is necessary for caches to be previously configured and running.

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

//Get a cache from manager via its string name.
javax.cache.Cache demoCache = manager.getCache("demoCache");
javax.cache.Cache productCache = manager.getCache("productCache");

Add/Update Data in Cache

After successful initialization and getting a cache handle, you can perform a put operation. It is a basic operation provided by JCache, and this can be used to add/update data to the cache using multiple API calls.

Adding Objects to Cache

In the following example, an object of a custom class is created and added to the cache. This item has all the properties provided in the code below and is added to the cache using the put method.

// Ensure that Cache is already initialized and the item exists.
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
String key = "Product:" + product.getProductID();

// Add data in cache with the values
jCache.put(key, product);

Update Data in Cache

In the following example, an object of a custom class is updated in the cache. The replace method overwrites the already existing value of the object.

Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
product.setUnitsInStock(5); // updated units.
String key = "Product:" + product.getProductID();

// Replace the item in the cache with updated item.
jCache.replace(key, product);

Add and Update Bulk Items in Cache

You can add and update an entire collection of items in the cache using the putAll method. This method returns a HashMap of all the keys that were not added along with the exception.

Product product1 = new Product("1001", "Chai");
String key1 = "Product:" + product1.getProductID();

Product product2 = new Product("1002", "Coffee");
String key2 = "Product:" + product2.getProductID();

// Data to add in cache
HashMap dataMap = new HashMap();
dataMap.put(key1, product1);
dataMap.put(key2, product2);

// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

// Add/Update all keys in the cache
jCache.putAll(dataMap);

Retrieve from Cache

JCache uses get method to retrieve a specific entry from the cache through key.

Retrieve a Single Item from the Cache

In the following example, we use the default get method to retrieve a pre-existing object, "Product:1001". This item already exists in the cache. The get method returns an object which needs to be cast accordingly. If a matching key does not exist in the cache, a null value is returned.

// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

// Key to get
String key = "Product:1001";

//Get specified item
Product product = (Product) jCache.get(key);
if (product != null) {
    // business logic
}

Retrieve Bulk Data from Cache

For fetching a collection from the cache, use the getAll method. This method returns a collection of items as a HashMap.

// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

HashSet keysToGet = new HashSet();
keysToGet.add("Product:1001");
keysToGet.add("Product:1002");

Map productsMap = jCache.getAll(keysToGet);
if (!productsMap.isEmpty())
{
    for (Iterator iter = productsMap.values().iterator(); iter.hasNext();)
    {
        Product product = (Product) iter.next();
        //utilize product object accordingly.
    }
}

Remove Data from Cache

JCache provides remove method to remove the mapping for an existing key from the cache.

Using Remove Method

The remove method in the JCache API removes mapping associated with a specified key from the cache, if it exists. The method returns true (if the cache contains the key and the removal was successful) or false (if there is no mapping for the key). The following example removes the key mappings for Product class.

// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

// Key to remove.
String key = "Product:1001";

// False is returned if key does not exist in cache.
boolean result = jCache.remove(key);
if (result != true) {
    //Deleted.
}
else {
//Failed.
}

Remove Bulk Data

The following code snippet removes the items in bulk from the cache through the removeAll method. The code gets an instance of the JCache Manager, obtains the required cache from the manager, and defines keys against which the data is to be removed.

// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

// Keys to remove
HashSet set = new HashSet();
set.add("Product:1001");
set.add("Product:1002");

// Removing all keys
jCache.removeAll(set);

Clear Cache

To clear the cache completely (in the background), you need to call the clear method.

// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");

// Clear the Cache.
jCache.clear();

See Also

Event Notifications in Cache
Hibernate Caching
NCache Java Session Module

In This Article
  • Prerequisites for JCache CRUD Operations
  • Initialize Cache
    • Obtaining NCache API's Cache Instance
    • Initialize Multiple Caches in a Single Application
  • Add/Update Data in Cache
    • Adding Objects to Cache
    • Update Data in Cache
    • Add and Update Bulk Items in Cache
  • Retrieve from Cache
    • Retrieve a Single Item from the Cache
    • Retrieve Bulk Data from Cache
  • Remove Data from Cache
    • Using Remove Method
    • Remove Bulk Data
  • Clear Cache
  • See Also

Contact Us

PHONE

+1 (214) 764-6933   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • NCache Enterprise
  • NCache Professional
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - 2025. All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top