Thursday, April 6, 2023

How to create cache for java and C++ projetcs

Cache

This method can reduce the time required to generate or fetch data in the software program, which leads increase in fast executions

  • Caching frameworks available for Java,
    • Ehcache
    • Guava
    • Caffeine
  • Create a cache instance
    • Specifying the cache size
    • Expiration policy
    • Configuration settings
  • Populate data to cache
    • Populate Data that is frequently accessed or generated
    • Examples are database results, API responses, or expensive computations.
  • Data Retrieving from the Cache:
    • Check if data is available in the current cache.
    • If available then return cached data
      • this reduces generating or fetching data.
    • If data is not available in the cache,
      • Generate or fetch data to be coached and add it to the cache
  • Manage cache eviction:
    • This is used To prevent them from overusing memory for cache
    • Remove less frequently used data from the cache by using an eviction policy that

Caffeine caching library example for cache data and requesting the data and adding data to cache

import com.github.benmanes.caffeine.cache.Cache;

import com.github.benmanes.caffeine.cache.Caffeine; import java.util.concurrent.TimeUnit; public class MyService

{ private final Cache<String, ExpensiveData> cache = Caffeine.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); public ExpensiveData getExpensiveData(String key)

    { ExpensiveData data = cache.getIfPresent(key); if (data == null)

        { data = generateExpensiveData(key); cache.put(key, data); } return data; } private ExpensiveData generateExpensiveData(String key)

    { // Generate expensive data here } }

  1. Above example, the Caffeine the library is used to create a cache
  2. Cache Size is set to 100 items
  3. The cache will Expire for items that are not accessed more than 10 minutes
  4. In getExpensiveData the method checks whether requested data based on key is avalble in the cache, it it in the cache it will return the item
  5. If the data is not available in the cache, it will generate data and add it to the cache
  6. so that in the next execution it can be used previously stored items from the cahce

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...