View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
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  }