docs: collecting parameter docs + formatting

This commit is contained in:
Ilkka Seppälä
2024-03-29 14:13:26 +02:00
parent ea7bc2a4eb
commit f80cc468b2
23 changed files with 1191 additions and 794 deletions
+67 -25
View File
@@ -10,7 +10,9 @@ tag:
## Intent
The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them again.
The caching pattern avoids expensive re-acquisition of resources by not releasing them immediately after use. The
resources retain their identity, are kept in some fast-access storage, and are re-used to avoid having to acquire them
again.
## Also known as
@@ -21,7 +23,10 @@ The caching pattern avoids expensive re-acquisition of resources by not releasin
Real world example
> A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each time a post is viewed becomes expensive, and it's a good idea to utilize caching here.
> A team is working on a website that provides new homes for abandoned cats. People can post their cats on the website
> after registering, but all the new posts require approval from one of the site moderators. The user accounts of the site
> moderators contain a specific flag and the data is stored in a MongoDB database. Checking for the moderator flag each
> time a post is viewed becomes expensive, and it's a good idea to utilize caching here.
In plain words
@@ -29,13 +34,20 @@ In plain words
Wikipedia says:
> In computing, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower data store; thus, the more requests that can be served from the cache, the faster the system performs.
> In computing, a cache is a hardware or software component that stores data so that future requests for that data can
> be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored
> elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot.
> Cache hits are served by reading data from the cache, which is faster than recomputing a result or reading from a slower
> data store; thus, the more requests that can be served from the cache, the faster the system performs.
**Programmatic Example**
Let's first look at the data layer of our application. The interesting classes are `UserAccount` which is a simple Java object containing the user account details, and `DbManager` interface which handles reading and writing of these objects to/from database.
Let's first look at the data layer of our application. The interesting classes are `UserAccount` which is a simple Java
object containing the user account details, and `DbManager` interface which handles reading and writing of these objects
to/from database.
```java
@Data
@AllArgsConstructor
@ToString
@@ -49,11 +61,15 @@ public class UserAccount {
public interface DbManager {
void connect();
void disconnect();
UserAccount readFromDb(String userId);
UserAccount writeToDb(UserAccount userAccount);
UserAccount updateDb(UserAccount userAccount);
UserAccount upsertDb(UserAccount userAccount);
}
```
@@ -62,17 +78,21 @@ In the example, we are demonstrating various different caching policies
* Write-through writes data to the cache and DB in a single transaction
* Write-around writes data immediately into the DB instead of the cache
* Write-behind writes data into the cache initially whilst the data is only written into the DB
* Write-behind writes data into the cache initially whilst the data is only written into the DB
when the cache is full
* Cache-aside pushes the responsibility of keeping the data synchronized in both data sources to
* Cache-aside pushes the responsibility of keeping the data synchronized in both data sources to
the application itself
* Read-through strategy is also included in the aforementioned strategies, and it returns data from
the cache to the caller if it exists, otherwise queries from DB and stores it into the cache for
* Read-through strategy is also included in the aforementioned strategies, and it returns data from
the cache to the caller if it exists, otherwise queries from DB and stores it into the cache for
future use.
The cache implementation in `LruCache` is a hash table accompanied by a doubly linked-list. The linked-list helps in capturing and maintaining the LRU data in the cache. When data is queried (from the cache), added (to the cache), or updated, the data is moved to the front of the list to depict itself as the most-recently-used data. The LRU data is always at the end of the list.
The cache implementation in `LruCache` is a hash table accompanied by a doubly linked-list. The linked-list helps in
capturing and maintaining the LRU data in the cache. When data is queried (from the cache), added (to the cache), or
updated, the data is moved to the front of the list to depict itself as the most-recently-used data. The LRU data is
always at the end of the list.
```java
@Slf4j
public class LruCache {
@@ -87,7 +107,7 @@ public class LruCache {
this.userAccount = userAccount;
}
}
/* ... omitted details ... */
public LruCache(int capacity) {
@@ -127,14 +147,21 @@ public class LruCache {
public boolean contains(String userId) {
return cache.containsKey(userId);
}
public void remove(Node node) { /* ... */ }
public void setHead(Node node) { /* ... */ }
public void invalidate(String userId) { /* ... */ }
public boolean isFull() { /* ... */ }
public UserAccount getLruData() { /* ... */ }
public void clear() { /* ... */ }
public List<UserAccount> getCacheDataInListForm() { /* ... */ }
public void setCapacity(int newCapacity) { /* ... */ }
}
```
@@ -142,6 +169,7 @@ public class LruCache {
The next layer we are going to look at is `CacheStore` which implements the different caching strategies.
```java
@Slf4j
public class CacheStore {
@@ -201,9 +229,13 @@ public class CacheStore {
}
```
`AppManager` helps to bridge the gap in communication between the main class and the application's back-end. DB connection is initialized through this class. The chosen caching strategy/policy is also initialized here. Before the cache can be used, the size of the cache has to be set. Depending on the chosen caching policy, `AppManager` will call the appropriate function in the `CacheStore` class.
`AppManager` helps to bridge the gap in communication between the main class and the application's back-end. DB
connection is initialized through this class. The chosen caching strategy/policy is also initialized here. Before the
cache can be used, the size of the cache has to be set. Depending on the chosen caching policy, `AppManager` will call
the appropriate function in the `CacheStore` class.
```java
@Slf4j
public final class AppManager {
@@ -223,7 +255,7 @@ public final class AppManager {
public UserAccount find(final String userId) {
LOGGER.info("Trying to find {} in cache", userId);
if (cachingPolicy == CachingPolicy.THROUGH
|| cachingPolicy == CachingPolicy.AROUND) {
|| cachingPolicy == CachingPolicy.AROUND) {
return cacheStore.readThrough(userId);
} else if (cachingPolicy == CachingPolicy.BEHIND) {
return cacheStore.readThroughWithWriteBackPolicy(userId);
@@ -257,12 +289,13 @@ public final class AppManager {
Here is what we do in the main class of the application.
```java
@Slf4j
public class App {
public static void main(final String[] args) {
boolean isDbMongo = isDbMongo(args);
if(isDbMongo){
if (isDbMongo) {
LOGGER.info("Using the Mongo database engine to run the application.");
} else {
LOGGER.info("Using the 'in Memory' database to run the application.");
@@ -308,7 +341,8 @@ public class App {
Use the Caching pattern when
* Repetitious acquisition, initialization, and release of the same resource cause unnecessary performance overhead
* In scenarios where the cost of recomputing or re-fetching data is significantly higher than storing and retrieving it from cache
* In scenarios where the cost of recomputing or re-fetching data is significantly higher than storing and retrieving it
from cache
* For read-heavy applications with relatively static data or data that changes infrequently
## Known Uses
@@ -316,28 +350,36 @@ Use the Caching pattern when
* Web page caching to reduce server load and improve response time
* Database query caching to avoid repeated expensive SQL queries
* Caching results of CPU-intensive computations
* Content Delivery Networks (CDNs) for caching static resources like images, CSS, and JavaScript files closer to the end users
* Content Delivery Networks (CDNs) for caching static resources like images, CSS, and JavaScript files closer to the end
users
## Consequences
Benefits:
* Improved Performance: Significantly reduces data access latency, leading to faster application performance
* Reduced Load: Decreases the load on the underlying data source, which can lead to cost savings and increased longevity of the resource
* Scalability: Enhances the scalability of applications by efficiently handling increases in load without proportional increases in resource utilization
* Reduced Load: Decreases the load on the underlying data source, which can lead to cost savings and increased longevity
of the resource
* Scalability: Enhances the scalability of applications by efficiently handling increases in load without proportional
increases in resource utilization
Trade-Offs:
* Complexity: Introduces complexity in terms of cache invalidation, consistency, and synchronization
* Resource Utilization: Requires additional memory or storage resources to maintain the cache
* Stale Data: There's a risk of serving outdated data if the cache is not properly invalidated or updated when the underlying data changes
* Stale Data: There's a risk of serving outdated data if the cache is not properly invalidated or updated when the
underlying data changes
## Related patterns
* [Proxy](https://java-design-patterns.com/patterns/proxy/): Caching can be implemented using the Proxy pattern, where the proxy object intercepts requests and returns cached data if available
* [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify the cache when the underlying data changes, so that it can be updated or invalidated accordingly
* [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add caching behavior to an existing object without modifying its code
* [Strategy](https://java-design-patterns.com/patterns/strategy/): Different caching strategies can be implemented using the Strategy pattern, allowing the application to switch between them at runtime
* [Proxy](https://java-design-patterns.com/patterns/proxy/): Caching can be implemented using the Proxy pattern, where
the proxy object intercepts requests and returns cached data if available
* [Observer](https://java-design-patterns.com/patterns/observer/): Can be used to notify the cache when the underlying
data changes, so that it can be updated or invalidated accordingly
* [Decorator](https://java-design-patterns.com/patterns/decorator/): Can be used to add caching behavior to an existing
object without modifying its code
* [Strategy](https://java-design-patterns.com/patterns/strategy/): Different caching strategies can be implemented using
the Strategy pattern, allowing the application to switch between them at runtime
## Credits