Extract common ID generation logic using IdBlockAllocator
- Define IdGenerator<T> interface
- Implement AbstractIdBlockAllocatorBasedIdGenerator<T>, which
has the common logic for the existing IntentId, FlowId, MatchActionId,
and MatchActionOperationsId generator implementations.
Change-Id: I7aeea249df1710719760ed477bffe62853577e0f
diff --git a/src/main/java/net/onrc/onos/core/util/AbstractBlockAllocatorBasedIdGenerator.java b/src/main/java/net/onrc/onos/core/util/AbstractBlockAllocatorBasedIdGenerator.java
new file mode 100644
index 0000000..851bb91
--- /dev/null
+++ b/src/main/java/net/onrc/onos/core/util/AbstractBlockAllocatorBasedIdGenerator.java
@@ -0,0 +1,40 @@
+package net.onrc.onos.core.util;
+
+/**
+ * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as
+ * backend.
+ *
+ * @param <T> the type of ID
+ */
+public abstract class AbstractBlockAllocatorBasedIdGenerator<T> implements IdGenerator<T> {
+ protected final IdBlockAllocator allocator;
+ protected IdBlock idBlock;
+
+ /**
+ * Constructs an ID generator which use {@link IdBlockAllocator} as backend.
+ *
+ * @param allocator
+ */
+ protected AbstractBlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) {
+ this.allocator = allocator;
+ this.idBlock = allocator.allocateUniqueIdBlock();
+ }
+
+ @Override
+ public synchronized T getNewId() {
+ try {
+ return convertFrom(idBlock.getNextId());
+ } catch (UnavailableIdException e) {
+ idBlock = allocator.allocateUniqueIdBlock();
+ return convertFrom(idBlock.getNextId());
+ }
+ }
+
+ /**
+ * Returns an ID instance of {@code T} type from the long value.
+ *
+ * @param value original long value
+ * @return ID instance
+ */
+ protected abstract T convertFrom(long value);
+}