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