View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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   * Value↔id map keyed by object identity ({@code ==} / {@link System#identityHashCode}),
24   * with access-order LRU eviction at {@code capacity}.
25   *
26   * <p>Equal-but-distinct instances are different keys. {@link #getIdByValue} and
27   * {@link #getValueById} count as uses. Evicted ids are reused for later inserts.
28   * {@code idToValue} is a plain {@link HashMap}; LRU order lives only in {@code valueToId}.
29   *
30   * @see SerializerBase.BiMapType#IDENTITY
31   */
32  public class BidirectionalObjectToIdMapIdentity<V> implements BidirectionalObjectToIdMap<V> {
33  
34      static final boolean ACCESS_ORDER = true;
35  
36      final int capacity;
37  
38      private final Map<Integer, V> idToValue;
39      private final LinkedHashMap<IdentityKey<V>, Integer> valueToId;
40      /** Reused for lookups so {@link #getIdByValue} / {@link #getValueById} do not allocate. */
41      private final IdentityKey<V> lookupKey = new IdentityKey<>(null);
42      private final SerializerIdPool idPool = new DualSerializerIdPool();
43  
44      public BidirectionalObjectToIdMapIdentity(int capacity) {
45          this.capacity = cappedSerializerCapacity(capacity);
46          this.idToValue = new HashMap<>(this.capacity);
47          this.valueToId = new LinkedHashMap<>(this.capacity, 0.75f, ACCESS_ORDER) {
48              @Override
49              protected boolean removeEldestEntry(Map.Entry<IdentityKey<V>, Integer> eldest) {
50                  if (size() > BidirectionalObjectToIdMapIdentity.this.capacity) {
51                      recycle(eldest.getValue());
52                      return true;
53                  }
54                  return false;
55              }
56          };
57      }
58  
59      @Override
60      public Integer getIdByValue(V value) {
61          lookupKey.ref = value;
62          Integer id = valueToId.get(lookupKey);
63          lookupKey.ref = null;
64          return id;
65      }
66  
67      @Override
68      public Integer insertNewEntryOnWrite(V value) {
69          ensureIdAvailable();
70          Integer boxed = idPool.allocate();
71          V existingValue = idToValue.put(boxed, value);
72          if (existingValue != null) {
73              valueToId.remove(IdentityKey.of(existingValue));
74          }
75          valueToId.put(IdentityKey.of(value), boxed);
76          return boxed;
77      }
78  
79      @Override
80      public V insertNewEntryOnRead(int id, V value) {
81          Integer boxed = BoxedIds.of(id);
82          idPool.unfree(boxed);
83          V existingValue = idToValue.put(boxed, value);
84          if (existingValue != null) {
85              valueToId.remove(IdentityKey.of(existingValue));
86          }
87          Integer previousId = valueToId.put(IdentityKey.of(value), boxed);
88          if (previousId != null && previousId.intValue() != id) {
89              recycle(previousId);
90          }
91          return existingValue;
92      }
93  
94      @Override
95      public V getValueById(int id) {
96          V value = idToValue.get(BoxedIds.of(id));
97          if (value != null) {
98              lookupKey.ref = value;
99              valueToId.get(lookupKey);
100             lookupKey.ref = null;
101         }
102         return value;
103     }
104 
105     private void ensureIdAvailable() {
106         if (!idPool.hasFree() && valueToId.size() >= capacity && !valueToId.isEmpty()) {
107             Map.Entry<IdentityKey<V>, Integer> eldest = valueToId.entrySet().iterator().next();
108             valueToId.remove(eldest.getKey());
109             recycle(eldest.getValue());
110         }
111     }
112 
113     private void recycle(Integer id) {
114         idToValue.remove(id);
115         idPool.recycle(id);
116     }
117 
118     static final class IdentityKey<V> {
119         V ref;
120 
121         static <V> IdentityKey<V> of(V ref) {
122             return new IdentityKey<>(ref);
123         }
124 
125         IdentityKey(V ref) {
126             this.ref = ref;
127         }
128 
129         @Override
130         public int hashCode() {
131             return System.identityHashCode(ref);
132         }
133 
134         @Override
135         public boolean equals(Object o) {
136             return o instanceof IdentityKey && ((IdentityKey<?>) o).ref == ref;
137         }
138     }
139 }