• Products
  • Solutions
  • Customers
  • Resources
  • Company
  • Pricing
  • Download
Try Playground
  • Server-side API Programming
  • Data Source Providers
  • Write-through
  • Use Write-through
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

Using Write-through with Cache Operations

This section explains the use of the Write-through provider after configuring and deploying it. NCache provides the Alachisoft.NCache.Runtime.Caching.WriteThruOptions class to specify WriteThru options in APIs. The WriteThruOptions class contains

  1. WriteThru updates data in the data source synchronously after updating the cache-store.
  2. WriteBehind updates data in the data source asynchronously after updating the cache-store.

Multiple Write-through providers can be configured through NCache. Default Write-through provider will be called if a specific provider name is not mentioned through API. You can also use providers other than default by using provider-specific overloads of APIs.

Note

Write-Through is [Deprecated] for NCache Java.

Prerequisites for Using Write-through

  • .NET
  • Java
  • Legacy API
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • For API details refer to: ICache, CacheItem, Get, Insert, InsertAsync, Remove, RemoveAsync, IWriteThruProvider.
  • To learn about the standard prerequisites required to work with all NCache server-side features please refer to the given page on Server Side API Prerequisites.
  • For API details refer to: CacheItem, insert, WriteThruProvider, remove, insertBulk, removeBulk, insertAsync, removeAsync.
  • Create a new Console Application.
  • Make sure that the data being added is serializable.
  • Add NCache References by locating %NCHOME%\NCache\bin\assembly\4.0 and adding Alachisoft.NCache.Web and Alachisoft.NCache.Runtime as appropriate.
  • Include the Alachisoft.NCache.Web.Caching and Alachisoft.NCache.Runtime.DatasourceProviders namespaces in your application.

Add/Update with Write-through

The following example creates a new cacheItem and adds this item in the cache with Write-through enabled, using the Insert() method. Using this method if the item is already present in the cache, the old value will be over-written with the new value.

  • .NET
  • Java
  • Legacy API
// Pre-Condition: Cache is already connected

// Fetch product with the given ProductID
Product product = FetchProductByProductID(1001);

// Specify the key of the item
string key = $"product.ProductID";
product.UnitPrice = 200;

// Create a new cacheItem with the product
var cacheItem = new CacheItem(product);

// Enable Write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

// Add the item in the cache with WriteThru enabled
CacheItemVersion itemVersion = cache.Insert(key, cacheItem, writeThruOptions);
// Pre-Condition: Cache is already connected
// Fetch product with the given ProductID
Product product = fetchProductByProductID(1001);

// Specify the key of the item
String key = product.getProductID();
product.setUnitPrice(200);

// Create a new cacheItem with the product
var cacheItem = new CacheItem(product);

// Enable Write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

// Add the item in the cache with WriteThru enabled
CacheItemVersion itemVersion = cache.insert(key,cacheItem,writeThruOptions);
Product product = new Product();
product.ProductID = 1001;
product.ProductName = "Chai";

CacheItem cacheItem = new CacheItem(product);
string key = "Product:" + product.ProductID;

CacheItemVersion updatedItemVersion;
updatedItemVersion = cache.Insert(key, cacheItem, DSWriteOption.WriteThru, "XmlWriteThruProvider", null);
  if (updatedItemVersion.Version > 1)
  {
      //Item updated in cache. Perform further tasks.
  }
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Bulk Operations

Add/Update Bulk Items with Write-through

The following example adds bulk items in the cache with Write-through enabled, using the InsertBulk() method. If the items are already present in the cache, new values overwrite the existing values.

  • .NET
  • Java
// Fetch all products from database
Product[] products = FetchProductsFromDB();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

IDictionary<string, CacheItem> dictionary = new Dictionary<string, CacheItem>();
foreach(var product in products)
{
  string key = $"Product:{product.ProductID}";
  var cacheItem = new CacheItem(product);
  dictionary.Add(key, cacheItem);
}

IDictionary<string, Exception> keysFailedToUpdate = cache.InsertBulk(dictionary, writeThruOptions);
// Fetch all products from database
Product[] products = fetchProductsFromDB();

var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

HashMap<String,CacheItem> distributedMap = new HashMap<String, CacheItem>();
for (var product: products) {
  String key = "Product:" + product.getProductID();
  var cacheItem = new CacheItem(product);
  distributedMap.put(key,cacheItem);
}

Map<String,Exception> keysFailedToUpdate = cache.insertBulk(distributedMap,writeThruOptions);

Remove Items in Bulk with Write-through

The following example removes a bulk of items from the cache with Write-Behind enabled, using the RemoveBulk() method.

  • .NET
  • Java
// Get Keys
Product[] products = FetchProductsFromDB();

// Specify keys to remove from cache
string[] keys = new string[products.Length];
int index = 0;

foreach (var product in products)
{
  keys[index] = $"Product:{product.ProductID}";
  index++;
}

// Create dictionary to store removed items
IDictionary<string, Product> removedItems = new Dictionary<string,Product>();

// Configure write thru
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

// Remove items with write-behind enabled
cache.RemoveBulk(keys, out removedItems, writeThruOptions);
// Get Keys
Product[] products = fetchProductsFromDB();

// Specify keys to remove from cache
String[] keys = new String[products.length];
int index = 0;
for (var product: products) {
  keys[index] = "Product" + product.getProductID();
  index++;
}

// Create dictionary to store removed items
Map<String,Product> removedItems = new HashMap<String,Product>();

// Configure write thru
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

// Remove items with write-behind enabled
cache.removeBulk(Arrays.asList(keys),writeThruOptions,Product.class);
Note

Use the method OnDataSourceItemsRemoved() to perform operations after data removal.

Remove an Existing Item with Write-through

The following example removes an item from the cache with Write-through enabled, using the Remove() method.

  • .NET
  • Java
  • Legacy API
// Specify the key of the item
string key = $"Product:{product.ProductID}";

// Enable Write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

// Remove the item corresponding to the key with Write-through enabled
cache.Remove(key, null, null, writeThruOptions);
// Specify the key of the item
String key = "Product:" + product.getProductID();

// Enable Write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

// Remove the item corresponding to the key with Write-through enabled
cache.remove(key,writeThruOptions,Product.class);
string key = "Product:1001";
Product product = null;

Object returnObject = cache.Remove(key, DSWriteOption.WriteThru, null);

//Verify the removed item from both cache and data source
if (returnObject != null)
{
    product = (Product)returnObject;
}

Asynchronous Operations

Add/Update Item with Write-through

The following example adds an item asynchronously in the cache with Write-through enabled, using the InsertAsync() method.

  • .NET
  • Java
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);

// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";

var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

// Add Product object to cache
Task task = cache.InsertAsync(key, cacheItem, writeThruOptions);
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);

// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();
var cacheItem = new CacheItem(product);

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

// Add Product object to cache
FutureTask task = cache.insertAsync(key,cacheItem,writeThruOptions);

Remove Item with Write-through

The following example removes existing items asynchronously from the cache with Write-through enabled, using the RemoveAsync() method.

  • .NET
  • Java
// Unique cache key of product to remove
string key = $"Product:{product.ProductID}";

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteThru;

// Asynchronously remove items from cache
Task<Product> task = cache.RemoveAsync<Product>(key, writeThruOptions);
// Unique cache key of product to remove
String key = "Product:" + product.getProductID();

// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);

// Asynchronously remove items from cache
FutureTask<Product> task = cache.removeAsync(key,writeThruOptions,Product.class);

Use Data Structures with Write-through

The following example uses different data structures with Write-through enabled, on the specified item.

  • .NET
  • Java
// Specify the key of the item
string key = $"Product:{product.ProductID}";
var dataTypeAttributes = new DataTypeAttributes();
var writeThruOptions = new WriteThruOptions(WriteMode.WriteThru, WriteThruProviderName);

switch(mainMenu)
{
  case mainMenu.GetDistributedCounter:
    // Modify or add count of the corresponding item with write thru enabled
    var distributedCounter = cache.DataTypeManager.CreateCounter("counter", dataTypeAttributes, 0, writeThruOptions);

    // perform operations on counter
    break;
  case mainMenu.GetDistributedDictionary:
    // Modify or add dictionary of the corresponding item with write thru enabled
    var distributedDictionary = cache.DataTypeManager.CreateDictionary<string, int>(key, dataTypeAttributes, writeThruOptions);

    // perform operations on dictionary
    break;
  case mainMenu.GetDistributedList:
    // Modify or add the list of the corresponding item with write thru enabled
    var distributedList = cache.DataTypeManager.CreateList<int>("list", dataTypeAttributes, writeThruOptions);

    // perform operations on list
    break;
  case mainMenu.GetDistributedQueue:
    // Modify or add the queue of the corresponding item with read thru enabled
    var distributedQueue = cache.DataTypeManager.CreateQueue<int>("queue", dataTypeAttributes, writeThruOptions);

    // perform operations on queue
    break;
  case mainMenu.GetDistributedHashSet:
    // Modify or add the HashSet of the corresponding item with read thru enabled
    var distributedHashSet = cache.DataTypeManager.CreateHashSet<int>("hashset", dataTypeAttributes, writeThruOptions);

    // perform operations on hashset
    break;
}
// Specify the key of the item
String key = "Product:" + product.getProductID();
DataStructureAttributes dataStructureAttributes = new DataStructureAttributes();

// Specify the WriteThruOptions
var writeThruOptions = new WriteThruOptions();
writeThruOptions.setMode(WriteMode.WriteThru);
writeThruOptions.getWriteThruOptions().setProviderName(WriteThruProviderName);

switch(mainMenu) {
  case GetDistributedCounter:
    // Modify or add counter of the corresponding item with write thru enabled
    Counter distributedCounter = cache.getDataStructuresManager().createCounter("counter", 0, dataStructureAttributes, writeThruOptions);

    // Perform operations on counter
    break;
  case GetDistributedDictionary:
    // Modify or add dictionary of the corresponding item with write thru enabled
    DistributedMap<String,Integer> distributedMap = cache.getDataStructuresManager().createMap<String,Integer>(key, dataStructureAttributes, writeThruOptions);

    // Perform operations on dictionary
    break;
  case GetDistributedList:
    // Modify or add list of the corresponding items with write thru enabled
    DistributedList<String,Integer> distributedList = cache.getDataStructuresManager().createList<String,Integer>("list", dataStructureAttributes, writeThruOptions);

    // Perform operations on list
    break;
  case GetDistributedQueue:
    // Modify or add the queue of the corresponding item with write thru enabled
    DistributedQueue<String,Integer> distributedQueue = cache.getDataStructuresManager().createQueue<String,Integer>("queue", dataStructureAttributes, writeThruOptions);

    // Perform operations on queue
    break;
  case GetDistributedHashSet:
    // Modify or add the HashSet of the corresponding item with write thru enabled
    DistributedHashSet<String,Integer> distributedHashSet = cache.getDataStructuresManager().createHashSet<String,Integer>("hashset", dataStructureAttributes, writeThruOptions);

    // Perform operations on hashset
    break;
}

Additional Resources

NCache provides sample application for Write-through on GitHub.

See Also

.NET: Alachisoft.NCache.Runtime namespace.
Java: com.alachisoft.ncache.runtime.datasourceprovider namespace.

In This Article
  • Prerequisites for Using Write-through
  • Add/Update with Write-through
  • Bulk Operations
    • Add/Update Bulk Items with Write-through
    • Remove Items in Bulk with Write-through
  • Remove an Existing Item with Write-through
  • Asynchronous Operations
    • Add/Update Item with Write-through
    • Remove Item with Write-through
  • Use Data Structures with Write-through
  • Additional Resources
  • 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