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.HashSet;
17  import java.util.Iterator;
18  
19  import static ch.qos.logback.core.kryo.KryoCoreConstants.MAX_SERIALIZER_ID;
20  
21  /**
22   * {@link SerializerIdPool} backed only by a {@link HashSet}. Recycle, allocate, and
23   * {@link #unfree} are all O(1); which free id is returned is unspecified.
24   */
25  final class SetSerializerIdPool implements SerializerIdPool {
26  
27      private final HashSet<Integer> free = new HashSet<>();
28      private int nextId = 1;
29  
30      @Override
31      public Integer allocate() {
32          if (!free.isEmpty()) {
33              Iterator<Integer> it = free.iterator();
34              Integer id = it.next();
35              it.remove();
36              return id;
37          }
38          if (nextId > MAX_SERIALIZER_ID) {
39              throw new IllegalStateException(
40                      "Serializer id exhausted (allowed 1.." + MAX_SERIALIZER_ID + ")");
41          }
42          return BoxedIds.of(nextId++);
43      }
44  
45      @Override
46      public boolean hasFree() {
47          return !free.isEmpty();
48      }
49  
50      @Override
51      public void recycle(Integer id) {
52          if (id != null) {
53              free.add(id);
54          }
55      }
56  
57      @Override
58      public void unfree(Integer id) {
59          if (id != null) {
60              free.remove(id);
61          }
62      }
63  }