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.ArrayDeque;
17 import java.util.HashSet;
18
19 import static ch.qos.logback.core.kryo.KryoCoreConstants.MAX_SERIALIZER_ID;
20
21 /**
22 * {@link SerializerIdPool} that keeps both an {@link ArrayDeque} (LIFO allocate/recycle)
23 * and a {@link HashSet} (O(1) {@link #unfree} without scanning the deque).
24 *
25 * <p>After {@code unfree}, the deque may still hold that id. {@link #allocate} polls until
26 * {@code freeSet.remove} succeeds; the loop is bounded by deque size because each iteration
27 * {@code pollLast}s.
28 */
29 final class DualSerializerIdPool implements SerializerIdPool {
30
31 /** LIFO of recycled ids; may contain stale entries that {@link #unfree} already dropped. */
32 private final ArrayDeque<Integer> freeArrayDeque = new ArrayDeque<>();
33
34 /**
35 * Ids that may be assigned again. Subset of (or equal to) {@link #freeArrayDeque}.
36 * {@link #unfree} removes here only, so a read-path reuse does not walk the deque.
37 */
38 private final HashSet<Integer> freeSet = new HashSet<>();
39
40 private int nextId = 1;
41
42 @Override
43 public Integer allocate() {
44 Integer id;
45 while ((id = freeArrayDeque.pollLast()) != null) {
46 if (freeSet.remove(id)) {
47 return id;
48 }
49 }
50 if (nextId > MAX_SERIALIZER_ID) {
51 throw new IllegalStateException(
52 "Serializer id exhausted (allowed 1.." + MAX_SERIALIZER_ID + ")");
53 }
54 return BoxedIds.of(nextId++);
55 }
56
57 @Override
58 public boolean hasFree() {
59 return !freeSet.isEmpty();
60 }
61
62 @Override
63 public void recycle(Integer id) {
64 if (id == null) {
65 return;
66 }
67 if (freeSet.add(id)) {
68 freeArrayDeque.addLast(id);
69 }
70 }
71
72 @Override
73 public void unfree(Integer id) {
74 if (id != null) {
75 freeSet.remove(id);
76 }
77 }
78 }