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 } }
- Above example, the
Caffeinethe library is used to create a cache - Cache Size is set to 100 items
- The cache will Expire for items that are not accessed more than 10 minutes
- In
getExpensiveDatathe method checks whether requested data based on key is avalble in the cache, it it in the cache it will return the item - If the data is not available in the cache, it will generate data and add it to the cache
- so that in the next execution it can be used previously stored items from the cahce
No comments:
Post a Comment