Skip to content

Commit 538fb49

Browse files
authored
Merge pull request #1 from devxadarsh/work
Updated capacity method
2 parents b70bf14 + 75b9f7e commit 538fb49

File tree

1 file changed

+16
-12
lines changed
  • src/main/java/com/thealgorithms/datastructures/caches

1 file changed

+16
-12
lines changed

src/main/java/com/thealgorithms/datastructures/caches/ARCCache.java

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,28 +19,32 @@
1919
*/
2020

2121
public class ARCCache<K, V> {
22-
private final int capacity;
2322
private final Map<K, V> cache;
2423
private final LinkedHashMap<K, Integer> usageCounts;
2524
private final int t1Capacity; // Capacity for the t1 cache
2625
private final int b1Capacity; // Capacity for the b1 cache
2726
private int totalCount;
28-
/**
29-
* Retrieves the value associated with the given key from the cache.
30-
* If the key is present in the cache, its usage count is incremented.
31-
*
32-
* @param key the key whose associated value is to be retrieved
33-
* @return the value associated with the key, or null if the key is not present in the cache
34-
*/
27+
28+
/**
29+
* This constructor initializes an ARCCache object with the given capacity and initializes other necessary fields
30+
*/
3531
public ARCCache(int capacity) {
36-
this.capacity = capacity;
3732
this.cache = new LinkedHashMap<>();
3833
this.usageCounts = new LinkedHashMap<>();
3934
this.t1Capacity = capacity / 2; // Capacity for the t1 cache
4035
this.b1Capacity = capacity - t1Capacity; // Capacity for the b1 cache
4136
this.totalCount = 0;
4237
}
4338

39+
/**
40+
* Returns the total capacity of the cache
41+
*
42+
* @return the total capacity of the cache
43+
*/
44+
private int capacity() {
45+
return t1Capacity + b1Capacity;
46+
}
47+
4448
/**
4549
* Retrieves the value associated with the given key from the cache.
4650
* If the key is present in the cache, its usage count is incremented.
@@ -65,7 +69,7 @@ public V get(K key) {
6569
* @param value the value to be associated with the specified key
6670
*/
6771
public void put(K key, V value) {
68-
if (cache.size() >= capacity) {
72+
if (cache.size() >= capacity()) {
6973
evict();
7074
}
7175
cache.put(key, value);
@@ -99,8 +103,8 @@ private void evict() {
99103
* Adjust the cache sizes based on t1capacity and b1capacity after eviction from cache
100104
*/
101105
private void adjustCacheSize() {
102-
if (cache.size() > capacity) {
103-
int excess = cache.size() - capacity;
106+
if (cache.size() > capacity()) {
107+
int excess = cache.size() - capacity();
104108
int t1Size = cache.size() - b1Capacity;
105109
while (excess > 0 && !cache.isEmpty()) {
106110
K keyToRemove = usageCounts.keySet().iterator().next();

0 commit comments

Comments
 (0)