Skip to content

Package: LruCache

LruCache

nameinstructionbranchcomplexitylinemethod
LruCache(int, Consumer)
M: 0 C: 12
100%
M: 0 C: 0
100%
M: 0 C: 1
100%
M: 0 C: 4
100%
M: 0 C: 1
100%
removeEldestEntry(Map.Entry)
M: 0 C: 14
100%
M: 0 C: 2
100%
M: 0 C: 2
100%
M: 0 C: 4
100%
M: 0 C: 1
100%

Coverage

1: /**
2: * Copyright (C) 2022 Czech Technical University in Prague
3: *
4: * This program is free software: you can redistribute it and/or modify it under
5: * the terms of the GNU General Public License as published by the Free Software
6: * Foundation, either version 3 of the License, or (at your option) any
7: * later version.
8: *
9: * This program is distributed in the hope that it will be useful, but WITHOUT
10: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11: * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12: * details. You should have received a copy of the GNU General Public License
13: * along with this program. If not, see <http://www.gnu.org/licenses/>.
14: */
15: package cz.cvut.kbss.jopa.sessions.cache;
16:
17: import java.net.URI;
18: import java.util.LinkedHashMap;
19: import java.util.Map;
20: import java.util.function.Consumer;
21:
22: class LruCache extends LinkedHashMap<LruCache.CacheNode, Object> {
23:
24: private final int capacity;
25: private final transient Consumer<CacheNode> removeCallback;
26:
27: LruCache(int initialCapacity, Consumer<CacheNode> removeCallback) {
28: super(initialCapacity, 1.0f, true);
29: this.capacity = initialCapacity;
30: this.removeCallback = removeCallback;
31: }
32:
33: @Override
34: protected boolean removeEldestEntry(Map.Entry<CacheNode, Object> eldest) {
35:• if (this.size() >= capacity) {
36: removeCallback.accept(eldest.getKey());
37: return true;
38: }
39: return false;
40: }
41:
42:
43: public static class CacheNode {
44: private final URI context;
45: private final Class<?> cls;
46: private final Object identifier;
47:
48: CacheNode(URI context, Class<?> cls, Object identifier) {
49: assert context != null;
50: assert cls != null;
51: assert identifier != null;
52:
53: this.context = context;
54: this.cls = cls;
55: this.identifier = identifier;
56: }
57:
58: public URI getContext() {
59: return context;
60: }
61:
62: public Class<?> getCls() {
63: return cls;
64: }
65:
66: public Object getIdentifier() {
67: return identifier;
68: }
69:
70: @Override
71: public boolean equals(Object o) {
72: if (this == o) {
73: return true;
74: }
75: if (o == null || getClass() != o.getClass()) {
76: return false;
77: }
78:
79: CacheNode cacheNode = (CacheNode) o;
80:
81: return context.equals(cacheNode.context) && cls.equals(cacheNode.cls) &&
82: identifier.equals(cacheNode.identifier);
83:
84: }
85:
86: @Override
87: public int hashCode() {
88: int result = context.hashCode();
89: result = 31 * result + cls.hashCode();
90: result = 31 * result + identifier.hashCode();
91: return result;
92: }
93: }
94: }