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