This repository has been archived by the owner on Dec 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCache.java
114 lines (103 loc) · 2.48 KB
/
Cache.java
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.util.LinkedList;
/**
* Implements a 1 level cache.
* The cache stores btree nodes in a linked list.
* Each node represents one open space in the cache.
*
* @author Ben Peterson
*/
public class Cache {
//cache
private LinkedList<BTreeNode> cache1;
//cache size
private final int CACHE_MAX_SIZE;
/**
* Constructor for one level cache.
*
* @param cache1Size Size for 1st-level cache
*/
public Cache(int cache1Size) {
//initialize class variables
cache1 = new LinkedList<BTreeNode>();
this.CACHE_MAX_SIZE = cache1Size;
}//end of Cache
/**
* Adds an object to the cache if it does not
* already exist. Moves object to front of the
* cache if it does exist.
*
* @param toAdd object to be added to the cache
*/
public BTreeNode addObject(BTreeNode toAdd) {
BTreeNode returnNode = null;
if (isFull()) {
returnNode = cache1.removeLast();
}
BTreeNode moveToFront = getObject(toAdd);
if (moveToFront == null){
cache1.addFirst(toAdd);
}
else { //already in cache move to front
cache1.addFirst(moveToFront);
}
return returnNode;
}//end of addObject
/**
* Looks for BTreeNode in cache and returns it if found.
*
* @param toGet object to check cache for
* @return BTreeNode if found, null if not found
*/
public BTreeNode getObject(BTreeNode toGet) {
//look for object in cache and return it if found
for (int i = 0; i < cache1.size(); i++) {
if (cache1.get(i).equals(toGet)) {
return cache1.remove(i);
}
}
//not found
return null;
}//end of getObject
/**
* Looks for BTreeNode by file offset in cache and returns it if found.
*
* @param toGet object to check cache for
* @return BTreeNode if found, null if not found
*/
public BTreeNode getObject(long fileOffset) {
//look for object in cache and return it if found
for (int i = 0; i < cache1.size(); i++) {
if (cache1.get(i).filePos == fileOffset) {
BTreeNode toReturn = cache1.remove(i);
cache1.addFirst(toReturn);
return toReturn;
}
}
//not found
return null;
}//end of getObject
/**
* Returns last node in the cache.
*
* @return last node in cache
*/
public BTreeNode getLast () {
return cache1.removeLast();
}
/**
* Checks if cache is full
*
* @return true if full false otherwise
*/
public boolean isFull() {
return cache1.size() == CACHE_MAX_SIZE;
}
/**
* Gets cache size
*
* @return cacheSize
*/
public int cacheSize() {
return cache1.size();
}
}//end of class Cache