Caching Techniques
Caching is a technique used in system design to improve the performance and efficiency of an application by storing frequently accessed data in a cache. The cache acts as a temporary storage that stores computed or retrieved data for subsequent access.
Caching can be applied at various levels within a system, including database caching, object caching, query result caching, and web page caching. Each level of caching serves a specific purpose and provides benefits such as:
- Improved response time: Caching reduces the need to perform expensive operations, such as database queries or calculations, by serving the cached data directly.
- Reduced load on resources: By serving cached data, system resources like databases or external APIs are utilized less frequently, reducing the overall load on these resources.
- Scalability: Caching can help improve the scalability of an application by reducing the load on the underlying resources and enabling the system to handle more user requests.
- Consistency: Caching can provide a consistent view of data by storing frequently accessed data in a cache and reducing the dependency on slower data sources.
To implement caching, a popular data structure used is a cache map or hash map. This data structure allows for efficient key-value pair storage and retrieval. Here's an example of a simple cache implementation in Java:
TEXT/X-JAVA
1// Cache class that implements a basic cache with a fixed capacity
2
3class Cache {
4 private int capacity;
5 private Map<String, String> cacheMap;
6
7 public Cache(int capacity) {
8 this.capacity = capacity;
9 this.cacheMap = new LinkedHashMap<>(capacity, 0.75f, true) {
10 @Override
11 protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
12 return size() > capacity;
13 }
14 };
15 }
16
17 public void put(String key, String value) {
18 cacheMap.put(key, value);
19 }
20
21 public String get(String key) {
22 return cacheMap.get(key);
23 }
24}
xxxxxxxxxx
35
}
class Main {
public static void main(String[] args) {
// Replace with your caching logic here
Cache cache = new Cache(100); // Create a cache with a capacity of 100
cache.put("key1", "value1"); // Add key-value pair to cache
cache.put("key2", "value2");
String value1 = cache.get("key1"); // Retrieve value from cache
System.out.println(value1); // Output: value1
String value2 = cache.get("key2");
System.out.println(value2); // Output: value2
}
}
class Cache {
private int capacity;
private Map<String, String> cacheMap;
public Cache(int capacity) {
this.capacity = capacity;
this.cacheMap = new LinkedHashMap<>(capacity, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > capacity;
}
};
}
public void put(String key, String value) {
cacheMap.put(key, value);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment