blob: 851bb91575c8a15e3471a5ed4d330703b7662f3c [file] [log] [blame]
Sho SHIMIZU7cd8a422014-08-27 16:05:21 -07001package net.onrc.onos.core.util;
2
3/**
4 * Base class of {@link IdGenerator} implementations which use {@link IdBlockAllocator} as
5 * backend.
6 *
7 * @param <T> the type of ID
8 */
9public abstract class AbstractBlockAllocatorBasedIdGenerator<T> implements IdGenerator<T> {
10 protected final IdBlockAllocator allocator;
11 protected IdBlock idBlock;
12
13 /**
14 * Constructs an ID generator which use {@link IdBlockAllocator} as backend.
15 *
16 * @param allocator
17 */
18 protected AbstractBlockAllocatorBasedIdGenerator(IdBlockAllocator allocator) {
19 this.allocator = allocator;
20 this.idBlock = allocator.allocateUniqueIdBlock();
21 }
22
23 @Override
24 public synchronized T getNewId() {
25 try {
26 return convertFrom(idBlock.getNextId());
27 } catch (UnavailableIdException e) {
28 idBlock = allocator.allocateUniqueIdBlock();
29 return convertFrom(idBlock.getNextId());
30 }
31 }
32
33 /**
34 * Returns an ID instance of {@code T} type from the long value.
35 *
36 * @param value original long value
37 * @return ID instance
38 */
39 protected abstract T convertFrom(long value);
40}