1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.omid.tso;
19
20 public class LongCache {
21
22 private final long[] cache;
23 private final int size;
24 private final int associativity;
25
26 public LongCache(int size, int associativity) {
27 this.size = size;
28 this.cache = new long[2 * (size + associativity)];
29 this.associativity = associativity;
30 }
31
32 public long set(long key, long value) {
33 final int index = index(key);
34 int oldestIndex = 0;
35 long oldestValue = Long.MAX_VALUE;
36 for (int i = 0; i < associativity; ++i) {
37 int currIndex = 2 * (index + i);
38 if (cache[currIndex] == key) {
39 oldestValue = 0;
40 oldestIndex = currIndex;
41 break;
42 }
43 if (cache[currIndex + 1] <= oldestValue) {
44 oldestValue = cache[currIndex + 1];
45 oldestIndex = currIndex;
46 }
47 }
48 cache[oldestIndex] = key;
49 cache[oldestIndex + 1] = value;
50 return oldestValue;
51 }
52
53 public long get(long key) {
54 final int index = index(key);
55 for (int i = 0; i < associativity; ++i) {
56 int currIndex = 2 * (index + i);
57 if (cache[currIndex] == key) {
58 return cache[currIndex + 1];
59 }
60 }
61 return 0;
62 }
63
64 private int index(long hash) {
65 return (int) (Math.abs(hash) % size);
66 }
67
68 }