1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.kryo;
15
16 import java.util.HashMap;
17 import java.util.LinkedHashMap;
18 import java.util.Map;
19
20 import static ch.qos.logback.core.kryo.KryoCoreConstants.cappedSerializerCapacity;
21
22
23
24
25
26
27
28
29
30 public class BidirectionalObjectToIdMapDefault<V> implements BidirectionalObjectToIdMap<V> {
31
32 static final boolean ACCESS_ORDER = true;
33
34 final int capacity;
35
36 private final Map<Integer, V> idToValue;
37 private final LinkedHashMap<V, Integer> valueToId;
38 private final SerializerIdPool idPool = new DualSerializerIdPool();
39
40 public BidirectionalObjectToIdMapDefault(int capacity) {
41 this.capacity = cappedSerializerCapacity(capacity);
42 this.idToValue = new HashMap<>(this.capacity);
43 this.valueToId = new LinkedHashMap<>(this.capacity, 0.75f, ACCESS_ORDER) {
44 @Override
45 protected boolean removeEldestEntry(Map.Entry<V, Integer> eldest) {
46 if (size() > BidirectionalObjectToIdMapDefault.this.capacity) {
47 recycle(eldest.getValue());
48 return true;
49 }
50 return false;
51 }
52 };
53 }
54
55 @Override
56 public Integer getIdByValue(V value) {
57 return valueToId.get(value);
58 }
59
60 @Override
61 public Integer insertNewEntryOnWrite(V value) {
62 ensureIdAvailable();
63 Integer boxed = idPool.allocate();
64 V existingValue = idToValue.put(boxed, value);
65 if (existingValue != null) {
66 valueToId.remove(existingValue);
67 }
68 valueToId.put(value, boxed);
69 return boxed;
70 }
71
72 @Override
73 public V insertNewEntryOnRead(int id, V value) {
74 Integer boxed = BoxedIds.of(id);
75 idPool.unfree(boxed);
76 V existingValue = idToValue.put(boxed, value);
77 if (existingValue != null) {
78 valueToId.remove(existingValue);
79 }
80 Integer previousId = valueToId.put(value, boxed);
81 if (previousId != null && previousId.intValue() != id) {
82 recycle(previousId);
83 }
84 return existingValue;
85 }
86
87 @Override
88 public V getValueById(int id) {
89 V value = idToValue.get(BoxedIds.of(id));
90 if (value != null) {
91 valueToId.get(value);
92 }
93 return value;
94 }
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109 private void ensureIdAvailable() {
110 if (!idPool.hasFree() && valueToId.size() >= capacity && !valueToId.isEmpty()) {
111 Map.Entry<V, Integer> eldest = valueToId.entrySet().iterator().next();
112 valueToId.remove(eldest.getKey());
113 recycle(eldest.getValue());
114 }
115 }
116
117 private void recycle(Integer id) {
118 idToValue.remove(id);
119 idPool.recycle(id);
120 }
121
122 Map<Integer, V> getIdToValueMap() {
123 return idToValue;
124 }
125
126 Map<V, Integer> getValueToIdMap() {
127 return valueToId;
128 }
129 }