-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCacheImplementation.java
More file actions
84 lines (65 loc) · 2.41 KB
/
LRUCacheImplementation.java
File metadata and controls
84 lines (65 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//Constraints
//1. Fixed size - The cache size is bounded.
//2. Faster access - Insert and search operations with O(1) time complexity
//3. Faster eviction - If the cache is full, remove the least recently used entity from the cache
//4. Enhancements - Evict the entries from both the map and list by using a scheduled executors service, i.e. Run the new thread to scan for all product data entries and remove the ones whose timestamp is older than current timestamp. Note, we need to store the time stamp as an attribute in product data.
public class LRUCacheImplementation {
private final int CACHE_SIZE = 1000;
private final Map<ProductData, ProductData> productCache = new HashMap<>();
private final LinkedList<ProductData> productList = new LinkedList<>();
public void putEntryIntoCache(final ProductData product) {
if(productCache.size() == CACHE_SIZE) {
ProductData lastEntry = productList.peekLast();
ProductData candidate = productCache.get(lastEntry);
productData.remove(candidate) // remove the last entry from the cache
productList.removeLast(); // remove the product data from the list to add new entries)
}
productCache.put(product, product);
productList.addFirst(product);
}
public ProductData getCacheEntry(final Product product) {
ProductData product productCache.get(product);
if(product != null) {
productList.remove(product);
productList.addFirst(product);
return product;
}
return null;
}
}
class ProductData {
private String manufacturer;
private String sku;
private double price;
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ProductData that = (ProductData) o;
return Double.compare(that.price, price) == 0 && manufacturer.equals(that.manufacturer) && sku.equals(that.sku);
}
@Override
public int hashCode() {
return Objects.hash(manufacturer, sku, price);
}
}