1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty5.util;
18
19 import java.util.concurrent.ConcurrentHashMap;
20 import java.util.concurrent.ConcurrentMap;
21 import java.util.concurrent.atomic.AtomicInteger;
22
23 import static io.netty5.util.internal.ObjectUtil.checkNonEmpty;
24 import static java.util.Objects.requireNonNull;
25
26
27
28
29
30
31 public abstract class ConstantPool<T extends Constant<T>> {
32
33 private final ConcurrentMap<String, T> constants = new ConcurrentHashMap<>();
34
35 private final AtomicInteger nextId = new AtomicInteger(1);
36
37
38
39
40 public T valueOf(Class<?> firstNameComponent, String secondNameComponent) {
41 return valueOf(
42 requireNonNull(firstNameComponent, "firstNameComponent").getName() + '#' +
43 requireNonNull(secondNameComponent, "secondNameComponent"));
44 }
45
46
47
48
49
50
51
52
53
54 public T valueOf(String name) {
55 return getOrCreate(checkNonEmpty(name, "name"));
56 }
57
58
59
60
61
62
63 private T getOrCreate(String name) {
64 T constant = constants.get(name);
65 if (constant == null) {
66 final T tempConstant = newConstant(nextId(), name);
67 constant = constants.putIfAbsent(name, tempConstant);
68 if (constant == null) {
69 return tempConstant;
70 }
71 }
72
73 return constant;
74 }
75
76
77
78
79 public boolean exists(String name) {
80 return constants.containsKey(checkNonEmpty(name, "name"));
81 }
82
83
84
85
86
87 public T newInstance(String name) {
88 return createOrThrow(checkNonEmpty(name, "name"));
89 }
90
91
92
93
94
95
96 private T createOrThrow(String name) {
97 T constant = constants.get(name);
98 if (constant == null) {
99 final T tempConstant = newConstant(nextId(), name);
100 constant = constants.putIfAbsent(name, tempConstant);
101 if (constant == null) {
102 return tempConstant;
103 }
104 }
105
106 throw new IllegalArgumentException(String.format("'%s' is already in use", name));
107 }
108
109 protected abstract T newConstant(int id, String name);
110
111 @Deprecated
112 public final int nextId() {
113 return nextId.getAndIncrement();
114 }
115 }