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 with access-order LRU eviction at {@code capacity}.
24   *
25   * <p>{@link #getIdByValue} and {@link #getValueById} count as uses, so entries that
26   * keep being looked up stay; the least-recently-used mapping is dropped when a new
27   * one would exceed capacity. Evicted ids are reused for later inserts. {@code idToValue}
28   * is a plain {@link HashMap}; LRU order lives only in {@code valueToId}.
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       * Makes a free id available before {@link SerializerIdPool#allocate()} on the write path.
98       *
99       * <p>Ids are assigned <em>before</em> {@code valueToId.put}, so LRU
100      * {@code removeEldestEntry} cannot supply the id for this insert. If the pool has
101      * nothing free and the map is already at {@link #capacity}, this drops the
102      * least-recently-used mapping and {@link #recycle(Integer) recycles} its id.
103      * {@code allocate()} then reuses that id instead of minting {@code nextId}, which
104      * would eventually exceed the 12-bit header.
105      *
106      * <p>No-op when a recycled id is already in the pool, or when the map is below
107      * capacity (a new id can be minted).
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 }