|
| 1 | +/** |
| 2 | + * ValueCache.java |
| 3 | + * |
| 4 | + * Copyright 2022 Heartland Software Solutions Inc. |
| 5 | + * |
| 6 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | + * you may not use this file except in compliance with the License. |
| 8 | + * 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 | + |
| 19 | +package ca.hss.math; |
| 20 | + |
| 21 | +public class ValueCache<T1,T2> { |
| 22 | + int m_numEntries; |
| 23 | + long m_call; |
| 24 | + |
| 25 | + static class Entry { |
| 26 | + long m_call = -1; |
| 27 | + Object m_key; |
| 28 | + Object m_value; |
| 29 | + }; |
| 30 | + |
| 31 | + Entry [] entries = null; |
| 32 | + |
| 33 | + public ValueCache(int numEntries) { |
| 34 | + m_numEntries = numEntries; |
| 35 | + entries = new Entry[m_numEntries]; |
| 36 | + for (int i = 0; i < m_numEntries; i++) |
| 37 | + entries[i] = new Entry(); |
| 38 | + } |
| 39 | + |
| 40 | + public void clear() { |
| 41 | + for (int i = 0; i < m_numEntries; i++) |
| 42 | + entries[i].m_call = -1; |
| 43 | + } |
| 44 | + |
| 45 | + public void put(T1 key, T2 value) { |
| 46 | + if (m_numEntries == 0) |
| 47 | + return; |
| 48 | + m_call++; |
| 49 | + if (m_call < 0) { |
| 50 | + clear(); |
| 51 | + m_call++; |
| 52 | + } |
| 53 | + |
| 54 | + int i, oldest = 0; |
| 55 | + for (i = 0; i < m_numEntries; i++) { |
| 56 | + if (entries[i].m_call == -1) |
| 57 | + break; |
| 58 | + if (entries[i].m_call < entries[oldest].m_call) |
| 59 | + oldest = i; |
| 60 | + if (entries[i].m_key.equals(key)) { |
| 61 | + entries[i].m_call = m_call; |
| 62 | + return; |
| 63 | + } |
| 64 | + } |
| 65 | + if (i == m_numEntries) |
| 66 | + i = oldest; |
| 67 | + |
| 68 | + entries[i].m_call = m_call; |
| 69 | + entries[i].m_key = key; |
| 70 | + entries[i].m_value = value; |
| 71 | + } |
| 72 | + |
| 73 | + @SuppressWarnings("unchecked") |
| 74 | + public T2 get(T1 key) { |
| 75 | + if (m_numEntries == 0) |
| 76 | + return null; |
| 77 | + |
| 78 | + for (int i = 0; i < m_numEntries; i++) { |
| 79 | + if (entries[i].m_call == -1) |
| 80 | + return null; |
| 81 | + if (entries[i].m_key.equals(key)) { |
| 82 | + m_call++; |
| 83 | + if (m_call < 0) { |
| 84 | + clear(); |
| 85 | + m_call++; |
| 86 | + } |
| 87 | + entries[i].m_call = m_call; |
| 88 | + return (T2)entries[i].m_value; |
| 89 | + } |
| 90 | + } |
| 91 | + return null; |
| 92 | + } |
| 93 | +} |
0 commit comments