|
11 | 11 | import java.io.Serial;
|
12 | 12 | import java.util.Objects;
|
13 | 13 | import java.util.UUID;
|
| 14 | +import java.util.concurrent.ConcurrentHashMap; |
| 15 | +import java.util.concurrent.atomic.AtomicReference; |
14 | 16 | import java.util.function.Function;
|
15 | 17 |
|
16 | 18 | /**
|
@@ -46,7 +48,7 @@ protected static <SelfType extends ObjectUuid<SelfType>> SelfType randomUUID(
|
46 | 48 | final Function<UUID, SelfType> constructor
|
47 | 49 | )
|
48 | 50 | {
|
49 |
| - return constructor.apply(ObjectUuidGenerator.randomUUid(constructor)); |
| 51 | + return constructor.apply(Generators.randomUuid(constructor)); |
50 | 52 | }
|
51 | 53 |
|
52 | 54 | @NotNull
|
@@ -211,4 +213,43 @@ private void readObject(final ObjectInputStream stream)
|
211 | 213 | throw new UnsupportedOperationException("Java Serialization is not supported. Do you have properly configured mapping for this type?");
|
212 | 214 | }
|
213 | 215 |
|
| 216 | + /** |
| 217 | + * This class exists for two reasons: 1) to allow reusing generator instances per-type 2) to allow configuring a different generators factory. |
| 218 | + * This could be useful, if you want e.g. deterministic IDs in your tests. |
| 219 | + */ |
| 220 | + public static final class Generators |
| 221 | + { |
| 222 | + |
| 223 | + private static final AtomicReference<UuidGenerator.Factory> FACTORY = new AtomicReference<>(new UuidGenerator.Factory.DefaultUuidV7GeneratorFactory()); |
| 224 | + |
| 225 | + private static final ConcurrentHashMap<Function<?, ?>, UuidGenerator> GENERATORS = new ConcurrentHashMap<>(); |
| 226 | + |
| 227 | + private Generators() |
| 228 | + { |
| 229 | + } |
| 230 | + |
| 231 | + static UUID randomUuid(final Function<?, ?> constructor) |
| 232 | + { |
| 233 | + return getGenerator(constructor).generate(); |
| 234 | + } |
| 235 | + |
| 236 | + static UuidGenerator getGenerator(final Function<?, ?> constructor) |
| 237 | + { |
| 238 | + return GENERATORS.computeIfAbsent( |
| 239 | + constructor, |
| 240 | + c -> FACTORY.get().getGenerator(c) |
| 241 | + ); |
| 242 | + } |
| 243 | + |
| 244 | + /** |
| 245 | + * Replaces the factory with provided implementation and throws away any pre-existing generators. |
| 246 | + */ |
| 247 | + static void setFactory(final UuidGenerator.Factory factory) |
| 248 | + { |
| 249 | + FACTORY.set(factory); |
| 250 | + GENERATORS.clear(); |
| 251 | + } |
| 252 | + |
| 253 | + } |
| 254 | + |
214 | 255 | }
|
0 commit comments