Sho SHIMIZU | 7cd8a42 | 2014-08-27 16:05:21 -0700 | [diff] [blame] | 1 | package 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 | */ |
| 9 | public 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 | } |